什么是将任务包装为任务的最佳方法

我正在编写一些异步辅助方法,我有API来支持TaskTask 。 为了重用代码,我希望基于Task的API将给定任务包装为Task并且只需调用Task API。

我可以这样做的一种方法是:

 private static async Task Convert(this Task @this) { await @this.ConfigureAwait(false); return false; } 

但是,我想知道:有没有更好/内置的方法来做到这一点?

没有现成的Task方法可以做到这一点,没有。 你的方法很好,很可能就像你能得到的一样简单。

使用任何其他方法实现适当的错误传播/取消语义看似很难。

更新后 ,以下内容传播exception和取消:

 public static class TaskExt { public static Task AsGeneric(this Task @this) { return @this.IsCompleted ? CompletedAsGeneric(@this) : @this.ContinueWith>(CompletedAsGeneric, TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } static Task CompletedAsGeneric(Task completedTask) { try { if (completedTask.Status != TaskStatus.RanToCompletion) // propagate exceptions completedTask.GetAwaiter().GetResult(); // return completed task return Task.FromResult(Empty.Value); } catch (OperationCanceledException ex) { // propagate cancellation if (completedTask.IsCanceled) // return cancelled task return new Task(() => Empty.Value, ex.CancellationToken); throw; } } } public struct Empty { public static readonly Empty Value = default(Empty); } 

我最近有同样的要求,我用自己的帮助扩展方法解决了它,它允许用户使用Task有效地包装一个Task

 public static async Task WithCompletionResult( this Task sourceTask, TResult result ) { await sourceTask; return result; } 

在您的示例中调用:

 Task task = myTask.WithCompletionResult(false); 

如果Task的结果无关紧要,我将使用:

 Task task = myTask.WithCompletionResult(null); 

我希望这有帮助。 如果有人知道这种方法的陷阱让我知道!

使用await似乎有点矫枉过正。 这里不需要状态机,只需使用ContinueWith

 private static Task Convert(this Task @this) { return @this.ContinueWith(p => { p.Wait(); return false;}); } 

注意:这将导致不幸地包装AggregateException