我有一个运行异步任务的任务收集器(评论的那个):
public Task<ResultOrException<T>[]> WhenAllOrException<T>(IEnumerable<Task<T>> tasks)
{
return Task.WhenAll(
tasks.Select(
task => task.ContinueWith(
t => t.IsFaulted
? new ResultOrException<T>(t.Exception)
: new ResultOrException<T>(t.Result))));
}
public class ResultOrException<T>
{
public ResultOrException(T result)
{
IsSuccess = true;
Result = result;
}
public ResultOrException(Exception ex)
{
IsSuccess = false;
Exception = ex;
}
public bool IsSuccess { get; }
public T Result { get; }
public Exception Exception { get; }
}
此代码等待所有任务,即使它们在 2 分钟后返回。我需要忽略所有超时为五秒的任务返回。
我也试过以这种方式更改我的代码,但它不会编译:
return Task.WhenAny(Task.WhenAll(
tasks.Select(
task => task.ContinueWith(
t => t.IsFaulted
? new ResultOrException<T>(t.Exception)
: new ResultOrException<T>(t.Result)))
), Task.Delay(2000));
或这个:
var ts = new TimeSpan(1000);
return await Task.WaitAll(
tasks.Select(
task => task.ContinueWith(
t => t.IsFaulted
? new ResultOrException<T>(t.Exception)
: new ResultOrException<T>(t.Result))),
ts);
如何做到这一点?
慕标琳琳
相关分类