await AsyncMethod() versus await await Task.Factory.StartNew(AsyncMethod)

前端 未结 2 1235
独厮守ぢ
独厮守ぢ 2021-02-06 03:37

Given the following method:

public async Task DoSomethingAsync() {
    // do some work
    await OpenSomeFileAsync();
    return new MyObject();
         


        
相关标签:
2条回答
  • 2021-02-06 03:59

    Yes, there is a difference: in the first form, you have an extra level of Task, which brings absolutely nothing useful.

    The first form is basically equivalent to this:

    Task<Task<MyObject>> task1 = Task.Factory.StartNew<Task<MyObject>>( DoSomethingAsync);
    Task<MyObject>> task2 = await task1;
    var myObject = await task2;
    

    So it doesn't really make sense: you're creating a task that just... creates another task.

    0 讨论(0)
  • 2021-02-06 04:00

    Most of the time, adding another Task is not useful, but in some cases, it can be.

    The difference is if you're on the UI thread (or something similar) and execute DoSomethingAsync() directly, its first part (// do some work) will also execute on the UI thread, and so will any continuation parts of the method (unless they use ConfigureAwait()). On the other hand, if you start another Task, both the first part and any following parts of DoSomethingAsync() will execute on the ThreadPool.

    If DoSomethingAsync() is written correctly, adding another Task shouldn't give you any advantages (and will give you the disadvantage of more overhead), but I can imagine there are cases where it will make a difference.

    Also, instead of using Task.Factory.StartNew() and two awaits, you could write:

    await Task.Run(DoSomethingAsync);
    
    0 讨论(0)
提交回复
热议问题