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();
Task t_MethodB = Task.Factory.StartNew(() =>
result = Services.GetResultsMethodB();
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(() =>
button1.Content = "Process";
button1.IsEnabled = true;
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.