用TPL解雇并忘记

时间:2017-08-07 10:44:01

标签: c# task-parallel-library

我有以下代码:

public void Func()
{
   ...
   var task = httpClient.PostAsync(...);

   var onlyOnRanToCompletionTask = task
            .ContinueWith(
                t => OnPostAsyncSuccess(t, notification, provider, account.Name),
                TaskContinuationOptions.OnlyOnRanToCompletion);

   var onlyOnFaultedTask = task
            .ContinueWith(
                t => OnPostAsyncAggregateException(t, notification.EntityId),
                TaskContinuationOptions.OnlyOnFaulted);

   return true;
}

Func不是异步的,我想要像火一样忘记,但有继续功能。我不想让该功能异步。场景是这个函数在某种循环中被调用,用于处理它们的对象组。对我来说问题似乎是当我们完成Func执行时,可以删除onlyOnRanToCompletionTask。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

但是您的代码应该按预期执行。简单的例子:

void Main()
{
    HandlingMyFuncAsync();
    Console.WriteLine("Doing some work, while 'fire and forget job is performed");
    Console.ReadLine();
}

public void HandlingMyFuncAsync()
{
    var task = MyFuncAsync();
    task.ContinueWith(t => Console.WriteLine(t), TaskContinuationOptions.OnlyOnRanToCompletion);
}

public async Task<string> MyFuncAsync()
{
    await Task.Delay(5000);
    return "A";
}

产生

  

做一些工作,同时执行“开火”和“忘记工作”

     

[5秒后结束]

     

A

答案 1 :(得分:1)

如果我是你,我会考虑使用Microsoft的Reactive Framework(Rx)。 Rx专为此类设计而设计。

这里有一些基本代码:

wc_booking

当我跑步时,我得到了这种输出:

+1 
+2 
+3 
 1-
!1!
 2-
!2!
 3-
!3!
Done.

它会触发所有来电并等待结果进入。它也让你知道它何时完成。

这是一个更实用的示例,展示了如何使用async和Rx返回结果:

void Main()
{
    int[] source = new [] { 1, 2, 3 };

    IObservable<int> query =
        from s in source.ToObservable()
        from u in Observable.Start(() => Func(s))
        select s;

    IDisposable subscription =
        query
            .Subscribe(
                x => Console.WriteLine($"!{x}!"),
                () => Console.WriteLine("Done."));
}

public void Func(int x)
{
    Console.WriteLine($"+{x} ");
    Thread.Sleep(TimeSpan.FromSeconds(1.0));
    Console.WriteLine($" {x}-");
}

这给出了:

+1 
+2 
+3 
 1-
!1,10!
 3-
 2-
!2,20!
!3,30!
Done.

在没有看到完整代码的情况下,我无法轻松地为您提供可以使用的完整示例,但Rx还将使用void Main() { int[] source = new [] { 1, 2, 3 }; var query = from s in source.ToObservable() from u in Observable.FromAsync(() => Func(s)) select new { s, u }; IDisposable subscription = query .Subscribe( x => Console.WriteLine($"!{x.s},{x.u}!"), () => Console.WriteLine("Done.")); } public async Task<int> Func(int x) { Console.WriteLine($"+{x} "); await Task.Delay(TimeSpan.FromSeconds(1.0)); Console.WriteLine($" {x}-"); return 10 * x; } 运算符来处理数据库上下文的关闭。

你可以通过Nugetting&#34; System.Reactive&#34;。

获得Rx