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
.
taskFile.txt
) and place it in your C: emp
folder:AsyncDemo
class, create a method called ReadBigFile()
that returns a Task<TResult>
type, which will be used to return an integer of bytes read from our big text file:public Task<int> ReadBigFile() { }
ReadAsync()
method that asynchronously reads a sequence of bytes from the stream and advances the position in that stream by the number of bytes read from that stream. You will also notice that we are using a buffer to read those bytes:public Task<int> ReadBigFile() { var bigFile = File.OpenRead(@"C: emp askFile.txt"); var bigFileBuffer = new byte[bigFile.Length]; var readBytes = bigFile.ReadAsync(bigFileBuffer, 0, (int)bigFile.Length); return readBytes; }
var readBytes = bigFile.ReadAsync(bigFileBuffer, 0, (int)bigFile.Length);
line that uses a lambda expression to specify the work that the task needs to perform. In this case, it is to read the bytes in the file:public Task<int> ReadBigFile() { var bigFile = File.OpenRead(@"C: emp askFile.txt"); var bigFileBuffer = new byte[bigFile.Length]; var readBytes = bigFile.ReadAsync(bigFileBuffer, 0, (int)bigFile.Length); readBytes.ContinueWith(task => { if (task.Status == TaskStatus.Running) Console.WriteLine("Running"); else if (task.Status == TaskStatus.RanToCompletion) Console.WriteLine("RanToCompletion"); else if (task.Status == TaskStatus.Faulted) Console.WriteLine("Faulted"); bigFile.Dispose(); }); return readBytes; }
namespace winformAsync { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } } }
button1_Click
event and add the async
keyword to the click event. This is an example of a void
returning an asynchronous method:private async void button1_Click(object sender, EventArgs e) { }
AsyncDemo
class's ReadBigFile()
method asynchronously. Remember to read the result from the method (which are the bytes read) into an integer variable:private async void button1_Click(object sender, EventArgs e) { Console.WriteLine("Start file read"); Chapter6.AsyncDemo oAsync = new Chapter6.AsyncDemo(); int readResult = await oAsync.ReadBigFile(); Console.WriteLine("Bytes read = " + readResult); }
Console.Writeline()
outputs as we have added them to the code in the Chapter6
class and in the Windows application.3.137.174.23