Create a completed Task

前端 未结 8 1935
名媛妹妹
名媛妹妹 2020-11-28 06:13

I want to create a completed Task (not Task). Is there something built into .NET to do this?

A related question: Create a complete

8条回答
  •  萌比男神i
    2020-11-28 07:00

    My preferred method for doing this is to call Task.WhenAll() with no arguments. The MSDN documentation states that "If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.". That sounds like what you want.

    Update: I found the source over at Microsoft's Reference Source; there you can see that Task.WhenAll contains the following:

    return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait
                Task.CompletedTask :
                new WhenAllPromise(tasks);
    

    So Task.CompletedTask is indeed internal, but it is exposed by calling WhenAll() with no arguments.

提交回复
热议问题