Task-Based Asynchronous Pattern (TAP) is now the recommended method to create asynchronous code. It executes asynchronously on a thread from the thread pool and does not execute synchronously on the main thread of your application. It allows us to check the task's state by calling the Status
property.
We will create a task to read a very large text file. This will be accomplished using an asynchronous Task
.
Create a large text file (we called ours
taskFile.txt
) and place it in yourC:\temp
folder:In the
AsyncDemo
class, create a method calledReadBigFile()
that returns aTask<TResult>
type, which will be used to return an integer of bytes read from our big text file:public Task<int> ReadBigFile() { }
Add the following code to open and read the file bytes. You will see that we are using the
ReadAsync()
method that asynchronously reads a sequence of bytes from the stream and advances the position in that stream...