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

前端 未结 2 1954
渐次进展
渐次进展 2021-01-17 17:54

I have two following methods

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

//overload with None token 
pu         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 18:34

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

    Func GetFunc()
    {
        Func 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 in hand, so just return it. Don't make a func that calls a func.

    If you had

    IEnumerable GetSequence()
    {
        IEnumerable 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.

提交回复
热议问题