• C# 5 …carry on awaiting

    by  • May 4, 2012 • .Net, Journal, Programming • 0 Comments

    This made me chuckle when I saw this.

    .Net 4 has the awesome Task.Factory.StartNew and .Net 4.5 added the syntactic sugar of Task.Run, but if you combine it with some of the functionality in C#5 the following code:

    int result = await Task.Run(async () => 
    { 
        await Task.Delay(1000); 
        return 42; 
    });
    

     

    When unwrapped becomes:

    int result = await await Task.Factory.StartNew(async delegate 
    { 
        await Task.Delay(1000); 
        return 42; 
    }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
    

     

    Yes you are seeing right, you are awaiting the await… Task.Factory.StartNew is returning a Task<Task<int>>.  Await’ing that Task<Task<int>> returns a Task<int>, and awaiting that Task<int> returns an int.

    About

    Software engineer. Tea drinker

    http://MrPfister.com

    Leave a Reply

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