如何在执行异步方法后调用成功的回调函数?

时间:2012-12-27 07:21:38

标签: c# .net asynchronous

我创建了一个类似下面的异步方法

 System.Threading.Tasks.Task.Factory.StartNew(
                                        () => AddAttachment(document, docId, user)).ContinueWith(
                                            task => BackUpQueuesMail(task.Exception, information, list),
                                            TaskContinuationOptions.OnlyOnFaulted);  

我需要在AddAttachment()方法成功处理后执行回调函数。我怎么能这样呢?

3 个答案:

答案 0 :(得分:3)

您需要提取AddAttachment任务,然后您可以使用continuation tasks指定主任务失败时要执行的任务,以及主任务成功完成时要执行的任务。

在此示例中, MethodToRunWhenFinishSuccessfully 将在 AddAttachment 完成时运行, BackUpQueuesMail 将在 AddAttachment 失败时运行。

var addAttachmentTask = Task.Factory.StartNew(() => AddAttachment(document, docId, user));
addAttachmentTask.ContinueWith(t => MethodToRunWhenFinishSuccessfully(t), TaskContinuationOptions.OnlyOnRanToCompletion);
addAttachmentTask.ContinueWith(t => BackUpQueuesMail(task.Exception, information, list), TaskContinuationOptions.OnlyOnFaulted);

答案 1 :(得分:2)

一种方法是:

System.Threading.Tasks.Task.Factory.StartNew(
                                        () => AddAttachment(document, docId, user)).ContinueWith(
                                            task => OnComplete(task), }
                                            TaskContinuationOptions.None);  


private void OnComplete(task)
{
   if(task.IsFaulted)
   {
   }
   else if(task.IsComplete) {}

}

答案 2 :(得分:0)

只需将OnlyOnFaulted更改为OnlyOnRanToCompletion