相关疑难解决方法(0)

如何将任务的已取消状态传播到延续任务

我在我的应用程序中使用任务并行库.我有一个任务(让我们称之为"DoSomething")可能被取消.无论任务是故障,取消还是成功完成,我都会继续执行该任务,执行一些清理工作.

在启动此任务的代码中,我想返回一个Task对象,其状态(出错,取消,运行完成)反映了DoSomething任务的状态,但重要的是我返回的这个任务不会反映这个状态,直到继续任务执行.

这是一个例子:

public Task Start(CancellationToken token)
{
    var doSomethingTask = Task.Factory.StartNew(DoSomething
                                                , token);

    var continuationTask = doSomethingTask.ContinueWith
                (
                 (antecedent) =>
                     {
                         if (antecedent.IsFaulted || antecedent.IsCanceled)
                         {
                             //Do failure-specific cleanup
                         }

   //Do general cleanup without regard to failure or success
                      }
                 );

//TODO: How do I return a Task obj which Status reflect the status of doSomethingTask,
//but will not transition to that status until continuationTask completes?
}
Run Code Online (Sandbox Code Playgroud)

我可以使用TaskCompletionSource,但这看起来很糟糕.还有其他想法吗?

c# .net-4.0 task-parallel-library c#-4.0

4
推荐指数
1
解决办法
903
查看次数

标签 统计

.net-4.0 ×1

c# ×1

c#-4.0 ×1

task-parallel-library ×1