C#如何在不等待异步方法完成的情况下启动异步方法? [英] C# How to start an async method without await its complete?

查看:125
本文介绍了C#如何在不等待异步方法完成的情况下启动异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我需要启动一个异步工作,该工作非常缓慢.我不在乎这项工作是否成功,我需要继续在当前线程上工作.

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.

就像有时我需要发送工作非常缓慢的电子邮件或SMS一样.我需要尽快响应Web客户端,所以我不想await.

Like sometimes I need to send an Email or SMS which works very slow. I need to respond to the web client as soon as possible so I don't want to await it.

我已经用谷歌搜索了这个问题,有些文章建议我这样写:

I have googled this question and some articles suggest me to write like this:

// This method has to be async
public async Task<Response> SomeHTTPAction()
{
    // Some logic...
    // ...

    // Send an Email but don't care if it successfully sent.
    Task.Run(() =>  _emailService.SendEmailAsync());
    return MyRespond();
}

或者像这样:

// This method has to be async
public async Task<Response> SomeHTTPAction()
{
    // Some logic...
    // ...

    // Send an Email but don't care if it successfully sent.
    Task.Factory.StartNew(() =>  _emailService.SendEmailAsync());
    return MyRespond();
}

会有警告说:before the call is completed. Consider applying the 'await' operator to the result of the call.

那如果我真的await怎么办呢?在C#中解雇"的最佳实践是什么,仅调用异步方法而不等待其完成?

So what if I really awaited it? What is the best practice in C# to 'fire and forget', just call an async method without waiting for its complete?

推荐答案

如果您真的只是想开枪而忘记.根本就不打电话给use await.

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

取消令牌允许中断和取消过程.如果您正在使用Cancellation令牌,则需要在从检索到调用方法的所有位置使用它(一直向下滚动).

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).

我使用了ConfigureAwait(false)来防止死锁. 此处有关更多信息

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

这篇关于C#如何在不等待异步方法完成的情况下启动异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆