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;
}

6 comments:

Unknown said...

Want to use this kind of functionality today? It's already available in F#. See Tomas Petricek's blog for a comparison: http://tomasp.net/blog/csharp-fsharp-async-intro.aspx

Unknown said...

@Robert,
Thanks for the reminder. I had seen the async functionality in F#, but for me the syntax rather obscured what was going on. When I saw the way they've done it in C# 5.0, I was able to grasp it intuitively - and therein lies Anders' genius!

Anonymous said...

It's just awesome right? :-)
And you can use the CTP today so :p

Anonymous said...

The comment says "Switch _BACK_ to UI thread". There are much more syntactically meaningful ways to enter and leave a operational context. How about something like this:

await(new SynchronizationContext.SwitchTo()) {
// Do cpu intensive work
}

I know, using a scope block to enclose a scope of operation; ground breaking.

When a developer calls AsyncSwitchToCPU from a thread that isn't the UI thread, this code does not "Return" to the UI thread; it enters the UI begins running on the UI thread potentially confusing the calling code.

alliance level guide expert Peter said...

I have seen the async functionality in F#, but for me the syntax rather obscured what was going on. With 5.0 I get understood is really fast.

Grant said...

Now that is elegant

Post a Comment