Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c# - Create a completed Task<T>

I'm implementing a method Task<Result> StartSomeTask() and happen to know the result already before the method is called. How do I create a Task<T> that has already completed?

This is what I'm currently doing:

private readonly Result theResult = new Result();

public override Task<Result> StartSomeTask()
{
    var task = new Task<Result>(() => theResult);
    task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread);
    return task;
}

Is there a better solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When targeting .NET 4.5 you can use Task.FromResult:

public static Task<TResult> FromResult<TResult>(TResult result);

To create a failed task, use Task.FromException:

public static Task FromException(Exception exception);
public static Task<TResult> FromException<TResult>(Exception exception);

.NET 4.6 adds Task.CompletedTask if you need a non generic Task.

public static Task CompletedTask { get; }

Workarounds for older versions of .NET:

  • When targeting .NET 4.0 with Async Targetting Pack (or AsyncCTP) you can use TaskEx.FromResult instead.

  • To get non-generic Task prior to .NET 4.6, you can use the fact that Task<T> derives from Task and just call Task.FromResult<object>(null) or Task.FromResult(0).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...