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.

How to do it…

  1. Create a large text file (we called ours taskFile.txt) and place it in your C: emp folder:
    How to do it…
  2. In the 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()
    {    
    
    }
  3. 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 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;
    }

    Note

    Exceptions you can expect to handle from the ReadAsync() method are ArgumentNullException, ArgumentOutOfRangeException, ArgumentException, NotSupportedException, ObjectDisposedException and InvalidOperatorException.

  4. Finally, add the final section of code just after the 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;
    }
  5. If not done so in the previous recipe, add a button to your Windows Forms application's Forms Designer. On the winformAsync form designer, open Toolbox and select the Button control, which is found under the All Windows Forms node:
    How to do it…
  6. Drag the button control onto the Form1 designer:
    How to do it…
  7. With the button control selected, double-click the control to create the click event in the code behind. Visual Studio will insert the event code for you:
    namespace winformAsync
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
            }
        }
    }
  8. Change the 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)
    {
    
    }
  9. Now, make sure that you add code to call the 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);
    }
  10. Running your application will display the Windows Forms application:
    How to do it…
  11. Before clicking on the button1 button, ensure that the Output window is visible:
    How to do it…
  12. From the View menu, click on the Output menu item or type Ctrl + Alt + O to display the Output window. This will allow us to see the Console.Writeline() outputs as we have added them to the code in the Chapter6 class and in the Windows application.
  13. Clicking on the button1 button will display the outputs in our Output window. Throughout this code execution, the form remains responsive:
    How to do it…

    Note

    Take note though that the information displayed in your Output window will differ from the screenshot. This is because the file you used is different from mine.

How it works…

The task is executed on a separate thread from the thread pool. This allows the application to remain responsive while the large file is being processed. Tasks can be used in multiple ways to improve your code. This recipe is but one example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.174.23