Handling tasks in asynchronous programming
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.
Getting ready
We will create a task to read a very large text file. This will be accomplished using an asynchronous Task
. Be sure that you have added the using System.IO;
namespace to your Windows forms application.
How to do it...
- Create a large text file (we called ours
taskFile.txt
) and place it in a folder calledC:\temp\taskFile\
:

- 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...