Saturday, September 24, 2011

Task-based Asynchronous Pattern

Here's a simple implementation of task-based asynchronous pattern

using System;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;

namespace TestAsync
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // inherently synchrononous operation
        public int ComputeSomething(int n)
        {
            // Problem is O(N)

            while (n-- > 0)
                Thread.Sleep(1000);

            return 7;
        }

        // Wrap the synchronous operation on Task-based Async Pattern to make the operation operate asynchronously
        Task<int> ComputeSomethingAsync(int n)
        {
            Task<int> t = new Task<int>(() =>
                {
                    return ComputeSomething(n);
                });

            t.Start();
            return t;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            // instead of doing things synchronously
            if (false)
            {
                int n = ComputeSomething(10);
                MessageBox.Show("Returned value is " + n.ToString());
            }

            // do things asynchronously instead
            if (true)
            {
                Task<int> t = ComputeSomethingAsync(10);
                t.ContinueWith(x =>
                {
                    if (x.IsFaulted)
                    {
                        MessageBox.Show(x.Exception.Message);
                    }
                    else
                    {
                        MessageBox.Show("Returned value is " + x.Result.ToString());
                    }

                });
            }

        }//button1_Click


    }//class Form1
}

For asynchronous operation, TAP asynchronous design pattern is easier to use than BeginXXX, EndXXX, IAsyncResult combo async pattern

On next C# version(C# 5), making routines asynchronous will be a lot easier with its built-in await and async functionality

No comments:

Post a Comment