async await on anonamous methods

时间:2015-09-01 22:56:24

标签: c# .net

This works

Task <string> t = Task <string> .Factory.StartNew(() => {
    return "test";
});

but if I change this to the below gives complilation error why?

Task <string> t = Task <string> .Factory.StartNew(asyc() => {
    await Thread.sleep(10000);
    return "test";
});

1 个答案:

答案 0 :(得分:1)

The reason for your issue is that the async method does not return a string but a Task<string>. So the correct return value for your function would be a Task<Task<string>>. Be aware that the outer task will be marked as completed as soon as the inner task is created and from that point forward you would have to wait for the inner task.

I suggest you are not using Task.Factory.StartNew but rather Task.Run since this function has a overload that properly handles async inner functions and unwraps the tasks. Using Task.Run is a good general idea, since you rarely need the Task created the way that Task.Factory.StartNew does.

So I suggest you change the code to:

Task<string> t = Task.Run(async () =>
    {
        await Task.Delay(10000);
        return "test";
    });

But if you are sure that you want to use Task.Factory.StartNew you can use this:

Task<Task<string>> t = Task.Factory.StartNew(async () =>
    {
        await Task.Delay(10000);
        return "test";
    });

EDIT: Just spotted that you are wrongly using Thread.Sleep. You need something that returns a Task to await it (or rather a awaitable object).

The function that does that for a delay is Task.Delay. This gives you a Task that can be awaited that completes after a set time.