问题描述
由于C#的任务是一个类,你显然不能投了任务< TDerived>
到任务< TBASE>
。
不过,你可以这样做:
公共异步任务< TBASE>跑() {
返回等待MethodThatReturnsDerivedTask();
}
有没有一种静态任务的方法我可以打电话获得任务< TDerived>
实例,它本质上只是指向底层的任务,并投下的结果呢?我想是这样的:
公共任务< TBASE>跑() {
返回Task.FromDerived(MethodThatReturnsDerivedTask());
}
请问这样的方法存在吗?是否有任何开销使用异步方法只用于此目的?
No.
Yes. But it's the easiest solution.
Note that a more generic approach is an extension method for Task
such as Then
. Stephen Toub explored this in a blog post and I've recently incorporated it into AsyncEx.
Using Then
, your code would look like:
public Task<TBase> Run()
{
return MethodThatReturnsDerivedTask().Then(x => (TBase)x);
}
Another approach with slightly less overhead would be to create your own TaskCompletionSource<TBase>
and have it completed with the derived result (using TryCompleteFromCompletedTask
in my AsyncEx library):
public Task<TBase> Run()
{
var tcs = new TaskCompletionSource<TBase>();
MethodThatReturnsDerivedTask().ContinueWith(
t => tcs.TryCompleteFromCompletedTask(t),
TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
or (if you don't want to take a dependency on AsyncEx):
public Task<TBase> Run()
{
var tcs = new TaskCompletionSource<TBase>();
MethodThatReturnsDerivedTask().ContinueWith(t =>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(t.Result);
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
这篇关于如何将任务&LT转换; TDerived&GT;给任务&LT; TBASE&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!