Tuesday, 2 November 2010

C# 5.0 and the sample that made me go “wow!”

In the Visual Studio Async CTP there is one sample project called 101 Asyncs. This is a browser displaying 101 code-snippets involving the new C# 5.0 async functionality. As I was flicking through I found the following sample, which I think speaks volumes for the elegance and simplicity of the feature:

public async void AsyncSwitchToCPU()
{
    Console.WriteLine("On the UI thread.");

    // Switch to a thread pool thread:
    await new SynchronizationContext().SwitchTo();  
                
    Console.WriteLine("Starting CPU-intensive work on background thread...");
    int result = DoCpuIntensiveWork();
    Console.WriteLine("Done with CPU-intensive work!");

    // Switch back to UI thread
    await Application.Current.Dispatcher.SwitchTo();                

    Console.WriteLine("Back on the UI thread.  Result is {0}.", result);
}

public int DoCpuIntensiveWork()
{
    // Simulate some CPU-bound work on the background thread:
    Thread.Sleep(5000);
    return 123;
}