33

假设以下同步代码:

try
{
    Foo();
    Bar();
    Fubar();
    Console.WriteLine("All done");
}
catch(Exception e) // For illustration purposes only. Catch specific exceptions!
{
    Console.WriteLine(e);
}

现在假设所有这些方法都有一个 Async 对应物,并且出于某种原因我必须使用它们,所以简单地将整个东西包装在一个新任务中不是一种选择。
我将如何实现相同的行为?
我所说的“相同”是:

  1. 如果抛出异常,则执行异常处理程序。
  2. 如果抛出异常,则停止执行以下方法。

我唯一能想到的是可怕的:

var fooTask = FooAsync();
fooTask.ContinueWith(t => HandleError(t.Exception),
                     TaskContinuationOptions.OnlyOnFaulted);
fooTask.ContinueWith(
    t =>
    {
        var barTask = BarAsync();
        barTask.ContinueWith(t => HandleError(t.Exception),
                             TaskContinuationOptions.OnlyOnFaulted);
        barTask.ContinueWith(
            t =>
            {
                var fubarTask = FubarAsync();
                fubarTask.ContinueWith(t => HandleError(t.Exception),
                                       TaskContinuationOptions.OnlyOnFaulted);
                fubarTask.ContinueWith(
                    t => Console.WriteLine("All done"),
                    TaskContinuationOptions.OnlyOnRanToCompletion);
            }, 
            TaskContinuationOptions.OnlyOnRanToCompletion);
    }, 
    TaskContinuationOptions.OnlyOnRanToCompletion);

请注意:

  • 我需要一个适用于 .NET 4 的解决方案,所以这async/await是不可能的。但是,如果它可以使用,请async/await随时展示如何。
  • 我不需要使用 TPL。如果 TPL 不可能,另一种方法也可以,也许使用 Reactive Extensions?
4

5 回答 5

31

以下是它的工作方式async

try
{
    await FooAsync();
    await BarAsync();
    await FubarAsync();
    Console.WriteLine("All done");
}
catch(Exception e) // For illustration purposes only. Catch specific exceptions!
{
    Console.WriteLine(e);
}

如果您安装了(预发布)Microsoft.Bcl.Async 包,这将适用于 .NET 4.0 。


由于您被困在 VS2010 上,您可以使用Stephen Toub 的Then变体:

public static Task Then(this Task first, Func<Task> next)
{
  var tcs = new TaskCompletionSource<object>();
  first.ContinueWith(_ =>
  {
    if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);
    else if (first.IsCanceled) tcs.TrySetCanceled();
    else
    {
      try
      {
        next().ContinueWith(t =>
        {
          if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);
          else if (t.IsCanceled) tcs.TrySetCanceled();
          else tcs.TrySetResult(null);
        }, TaskContinuationOptions.ExecuteSynchronously);
      }
      catch (Exception exc) { tcs.TrySetException(exc); }
    }
  }, TaskContinuationOptions.ExecuteSynchronously);
  return tcs.Task; 
}

您可以这样使用它:

var task = FooAsync().Then(() => BarAsync()).Then(() => FubarAsync());
task.ContinueWith(t =>
{
  if (t.IsFaulted || t.IsCanceled)
  {
    var e = t.Exception.InnerException;
    // exception handling
  }
  else
  {
    Console.WriteLine("All done");
  }
}, TaskContinuationOptions.ExcecuteSynchronously);

使用 Rx,它看起来像这样(假设您没有async已经公开的方法IObservable<Unit>):

FooAsync().ToObservable()
    .SelectMany(_ => BarAsync().ToObservable())
    .SelectMany(_ => FubarAsync().ToObservable())
    .Subscribe(_ => { Console.WriteLine("All done"); },
        e => { Console.WriteLine(e); });

我认为。无论如何,我不是 Rx 大师。:)

于 2013-01-31T16:51:05.403 回答
6

只是为了完整起见,这就是我将如何实现 Chris Sinclair 建议的辅助方法:

public void RunSequential(Action onComplete, Action<Exception> errorHandler,
                          params Func<Task>[] actions)
{
    RunSequential(onComplete, errorHandler,
                  actions.AsEnumerable().GetEnumerator());
}

public void RunSequential(Action onComplete, Action<Exception> errorHandler,
                          IEnumerator<Func<Task>> actions)
{
    if(!actions.MoveNext())
    {
        onComplete();
        return;
    }

    var task = actions.Current();
    task.ContinueWith(t => errorHandler(t.Exception),
                      TaskContinuationOptions.OnlyOnFaulted);
    task.ContinueWith(t => RunSequential(onComplete, errorHandler, actions),
                      TaskContinuationOptions.OnlyOnRanToCompletion);
}

这确保了每个后续任务仅在前一个任务成功完成时才被请求。
它假定Func<Task>返回一个已经在运行的任务。

于 2013-01-31T17:38:41.813 回答
5

你在这里所拥有的本质上是一个ForEachAsync. 您希望按顺序运行每个异步项目,但需要一些错误处理支持。这是一种这样的实现:

public static Task ForEachAsync(IEnumerable<Func<Task>> tasks)
{
    var tcs = new TaskCompletionSource<bool>();

    Task currentTask = Task.FromResult(false);

    foreach (Func<Task> function in tasks)
    {
        currentTask.ContinueWith(t => tcs.TrySetException(t.Exception.InnerExceptions)
            , TaskContinuationOptions.OnlyOnFaulted);
        currentTask.ContinueWith(t => tcs.TrySetCanceled()
                , TaskContinuationOptions.OnlyOnCanceled);
        Task<Task> continuation = currentTask.ContinueWith(t => function()
            , TaskContinuationOptions.OnlyOnRanToCompletion);
        currentTask = continuation.Unwrap();
    }

    currentTask.ContinueWith(t => tcs.TrySetException(t.Exception.InnerExceptions)
            , TaskContinuationOptions.OnlyOnFaulted);
    currentTask.ContinueWith(t => tcs.TrySetCanceled()
            , TaskContinuationOptions.OnlyOnCanceled);
    currentTask.ContinueWith(t => tcs.TrySetResult(true)
            , TaskContinuationOptions.OnlyOnRanToCompletion);

    return tcs.Task;
}

我还添加了对取消任务的支持,只是为了更笼统,因为它需要做的事情很少。

它将每个任务添加为前一个任务的延续,并且始终确保任何异常都会导致最终任务的异常被设置。

这是一个示例用法:

public static Task FooAsync()
{
    Console.WriteLine("Started Foo");
    return Task.Delay(1000)
        .ContinueWith(t => Console.WriteLine("Finished Foo"));
}

public static Task BarAsync()
{
    return Task.Factory.StartNew(() => { throw new Exception(); });
}

private static void Main(string[] args)
{
    List<Func<Task>> list = new List<Func<Task>>();

    list.Add(() => FooAsync());
    list.Add(() => FooAsync());
    list.Add(() => FooAsync());
    list.Add(() => FooAsync());
    list.Add(() => BarAsync());

    Task task = ForEachAsync(list);

    task.ContinueWith(t => Console.WriteLine(t.Exception.ToString())
        , TaskContinuationOptions.OnlyOnFaulted);
    task.ContinueWith(t => Console.WriteLine("Done!")
        , TaskContinuationOptions.OnlyOnRanToCompletion);
}
于 2013-01-31T18:26:41.927 回答
3

您应该能够创建一个方法来组合两个任务,并且只有在第一个成功时才启动第二个。

public static Task Then(this Task parent, Task next)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    parent.ContinueWith(pt =>
    {
        if (pt.IsFaulted)
        {
            tcs.SetException(pt.Exception.InnerException);
        }
        else
        {
            next.ContinueWith(nt =>
            {
                if (nt.IsFaulted)
                {
                    tcs.SetException(nt.Exception.InnerException);
                }
                else { tcs.SetResult(null); }
            });
            next.Start();
        }
    });
    return tcs.Task;
}

然后,您可以将任务链接在一起:

Task outer = FooAsync()
    .Then(BarAsync())
    .Then(FubarAsync());

outer.ContinueWith(t => {
    if(t.IsFaulted) {
        //handle exception
    }
});

如果您的任务立即开始,您可以将它们包装在一个Func

public static Task Then(this Task parent, Func<Task> nextFunc)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    parent.ContinueWith(pt =>
    {
        if (pt.IsFaulted)
        {
            tcs.SetException(pt.Exception.InnerException);
        }
        else
        {
            Task next = nextFunc();
            next.ContinueWith(nt =>
            {
                if (nt.IsFaulted)
                {
                    tcs.SetException(nt.Exception.InnerException);
                }
                else { tcs.SetResult(null); }
            });
        }
    });
    return tcs.Task;
}
于 2013-01-31T17:30:31.170 回答
1

现在,我并没有真正使用过多的 TPL,所以这只是在黑暗中刺伤。鉴于@Servy 提到的内容,也许这不会完全异步运行。但我想我会发布它,如果它偏离了标记,你可以否决我,或者我可以删除它(或者我们可以修复需要修复的内容)

public void RunAsync(Action onComplete, Action<Exception> errorHandler, params Action[] actions)
{
    if (actions.Length == 0)
    {
        //what to do when no actions/tasks provided?
        onComplete();
        return;
    }

    List<Task> tasks = new List<Task>(actions.Length);
    foreach(var action in actions)
    {
        Task task = new Task(action);
        task.ContinueWith(t => errorHandler(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
        tasks.Add(task);
    }

    //last task calls onComplete
    tasks[actions.Length - 1].ContinueWith(t => onComplete(), TaskContinuationOptions.OnlyOnRanToCompletion);

    //wire all tasks to execute the next one, except of course, the last task
    for (int i = 0; i <= actions.Length - 2; i++)
    {
        var nextTask = tasks[i + 1];
        tasks[i].ContinueWith(t => nextTask.Start(), TaskContinuationOptions.OnlyOnRanToCompletion);
    }

    tasks[0].Start();
}

它的用法如下:

RunAsync(() => Console.WriteLine("All done"),
            ex => Console.WriteLine(ex),
            Foo,
            Bar,
            Fubar);

想法?否决票?:)

(虽然我绝对更喜欢 async/await)

编辑:根据您的评论Func<Task>,这将是一个正确的实施吗?

public void RunAsync(Action onComplete, Action<Exception> errorHandler, params Func<Task>[] actions)
{
    if (actions.Length == 0)
    {
        //what to do when no actions/tasks provided?
        onComplete();
        return;
    }

    List<Task> tasks = new List<Task>(actions.Length);
    foreach (var action in actions)
    {
        Func<Task> nextActionFunc = action;
        Task task = new Task(() =>
        {
            var nextTask = nextActionFunc();
            nextTask.ContinueWith(t => errorHandler(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            nextTask.Start();
        });
        tasks.Add(task);
    }

    //last task calls onComplete
    tasks[actions.Length - 1].ContinueWith(t => onComplete(), TaskContinuationOptions.OnlyOnRanToCompletion);

    //wire all tasks to execute the next one, except of course, the last task
    for (int i = 0; i <= actions.Length - 2; i++)
    {
        var nextTask = tasks[i + 1];
        tasks[i].ContinueWith(t => nextTask.Start(), TaskContinuationOptions.OnlyOnRanToCompletion);
    }

    tasks[0].Start();
}
于 2013-01-31T17:06:44.607 回答