Should method that get Task and passes it away await it?

狂风中的少年 提交于 2019-12-01 14:48:00

问题


I have two following methods

public async Task<bool> DoSomething(CancellationToken.token) 
{
    //do something async
}

//overload with None token 
public /*async*/ Task<bool> DoSomething()
{
    return /*await*/ DoSomething(CancellationToken.None);
}

Should second method be marked with async/await keywords or not?


回答1:


It doesn't need to - if you use await/async in the second method, you'll be adding extra overhead which accomplishes nothing, in this case.

The async work inside of DoSomething(CancellationToken) will already provide the proper asynchronous handling and marshaling back to the existing context for you.

At the end of the day, async and await are really just language features which make it easy to create and compose a Task. If you already have a perfectly good Task to return, there is no need to use extra language support to unwrap and rewrap it into a new Task.




回答2:


To add to Reed's good answer, think about it this way:

Func<int, int> GetFunc()
{
    Func<int, int> f = GetFunc(someParameter);

Should you say

    return f;

or reason "I'm supposed to be returning a func here, so let's make a lambda that calls the func I have in hand":

    return (int i) => f(i);

I hope you would do the former; you already have a Func<int, int> in hand, so just return it. Don't make a func that calls a func.

If you had

IEnumerable<int> GetSequence()
{
    IEnumerable<int> sequence = GetSequence(someParameter);

would you say

    return sequence;

or

    foreach(int item in sequence) yield return item;

? Again, I hope you would do the former. You have a sequence in hand, so why go to all the trouble of making a new sequence that enumerates the old one?

The same goes for tasks; just like you can make a delegate that wraps another delegate and a sequence that wraps another sequence, you can make a task that wraps another task, but why would you? It's just a waste of resources.



来源:https://stackoverflow.com/questions/15444271/should-method-that-get-task-and-passes-it-away-await-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!