C# How to start an async method without await its complete?

前端 未结 6 1446
醉酒成梦
醉酒成梦 2021-02-05 08:12

Sometimes I need to start an async job which works very slow. I don\'t care if that job success and I need to continue working on my current thread.

Like sometimes I nee

6条回答
  •  太阳男子
    2021-02-05 08:44

    If you truly just want to fire and forget. Simply don't call use await.

    // It is a good idea to add CancellationTokens
    var asyncProcedure = SomeHTTPAction(cancellationToken).ConfigureAwait(false);
    
    // Or If not simply do:
    var asyncProcedure = SomeHTTPAction().ConfigureAwait(false);
    

    If you want to use the result output later its gets trickier. But if it is truly fire and forget the above should work

    A Cancellation token allows interrupts and canceling procedures. If you are using Cancellation token you will need to use it everywhere from the retrieval straight through to the calling method (Turtles all the way down).

    I used ConfigureAwait(false) to prevent deadlocks. Here for more information

提交回复
热议问题