So many times I have shunned away from doing Async programming. Most commonly because the programs that I write are simple and needed in a hurry. Even though using Async would have allowed for a better user experience and better performance. I never have been a fan of the current Async programming models, however TPL has caught my eye. So lets look at a few quick examples…

So, in my first example I have two simple web services that get the same data from different sources. Neither is particularly reliable or fast, so what I want to to is to hit both at the same time, and take which ever one comes back first, that way I can provide the best user experience. I’ve done this through a simple console application.

 static void Main(string[] args)
        {
            List<Task> tasks = new List<Task>();
            CancellationTokenSource cancelToken = new CancellationTokenSource(); 

            string result = String.Empty;

            Task t_MethodA = Task.Factory.StartNew(() =>
                {
                    result = Services.GetResultsMethodA();
                    cancelToken.Token.ThrowIfCancellationRequested(); 
                },cancelToken.Token);
            Task t_MethodB = Task.Factory.StartNew(() =>
                {
                    result = Services.GetResultsMethodB();
                    cancelToken.Token.ThrowIfCancellationRequested(); 
                },cancelToken.Token);

            tasks.Add(t_MethodA);
            tasks.Add(t_MethodB);

            Task.WaitAny(tasks.ToArray());
            cancelToken.Cancel(); 

            Console.WriteLine(result);
            Console.ReadKey();
        }

Now for you windows programmers, lets look at a quick WPF example where were doing to do a simple Async call to grab some data, and place it in a text box for the user to later manipulate.

private void button1_Click(object sender, RoutedEventArgs e)
        {
            button1.Content = "Processing...";
            button1.IsEnabled = false;

            Task t = Task.Factory.StartNew(() =>
                {
                    System.Threading.Thread.Sleep(5000);

                }).ContinueWith(o => 
                {
                    button1.Content = "Process";
                    button1.IsEnabled = true; 

                },TaskScheduler.FromCurrentSynchronizationContext()); 
        }

Using this method the user can still access the user interface because the UI thread isn’t locked, and will allow them to update other fields, do other processing, and avoid the “(not responding)” dialog we’re all custom to.

Now something new, because I think retyping is annoying, I’m putting my samples solution on CodePlex located here.

Tagged on:         

2 thoughts on “A Very Simple Introduction to the Task Parallel Library (TPL) in C#

  • January 10, 2014 at 9:31 am
    Permalink

    Hi Brad, nice article,

    you should really change the color scheme. its pretty horrendous

    Reply
  • May 3, 2014 at 6:45 am
    Permalink

    I concur. The article is great but the code-sections with black text are horribly colored.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>