I’m trying out the new async and await keywords using VS2012RC and .NET 4.5 with just a simple delegate that returns a string, which works fine when I run a single one:
string message = await Task.Run(() => { return "something"; });
but when I try WhenAny:
string message = await Task.WhenAny(new Task<string>(() => { return "something"; })).Result;
it just never completes…why?
I’ve been watching a video by Steve Sanderson from TechDays 2012 Netherlands which makes this look really easy: http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2287
When you create a
Taskusing its constructor, it’s not started yet. You have to callStart()to actually start it.I think you should to use
Task.Run()in your second version too, which returns you aTaskthat’s already started.Also, it’s a bad idea to mix asynchronous waiting (
await) with synchronous waiting (ResultorWait()), because it can lead to a deadlock.So, I would write your code as:
(Of course, there is no reason to use
Task.WhenAny()when you have only oneTask, but I’m assuming this is just an example.)