Create a completed Task

前端 未结 8 1963
名媛妹妹
名媛妹妹 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条回答
  •  不知归路
    2020-11-28 06:50

    Task is implicitly convertable to Task, so just get a completed Task (with any T and any value) and use that. You can use something like this to hide the fact that an actual result is there, somewhere.

    private static Task completedTask = Task.FromResult(false);
    public static Task CompletedTask()
    {
        return completedTask;
    }
    

    Note that since we aren't exposing the result, and the task is always completed, we can cache a single task and reuse it.

    If you're using .NET 4.0 and don't have FromResult then you can create your own using TaskCompletionSource:

    public static Task FromResult(T value)
    {
        var tcs = new TaskCompletionSource();
        tcs.SetResult(value);
        return tcs.Task;
    }
    

提交回复
热议问题