没有等待语句的C#异步任务 [英] c# async task with no await statement

查看:99
本文介绍了没有等待语句的C#异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从c#开发开始,我一直在努力进行异步编程,我对异步执行任务有疑问.

I'm just starting with c# development, and i always strugled with asyncronous programming,Ii have a doubt about performing a task asyncrounously.

我有自己的服务,能够发送电子邮件(不进行详细说明,但可以正常工作),并且我希望该方法的执行异步运行,我一直在阅读有关异步和等待的msdn文档.

I have my own service capable of sending an email (not going into details but its working) and I want that the execution of that method runs asyncronously, I've been reading in msdn documentation about async and await.

我确实想异步发送它,但是我不在乎结果,我的意思是我不想指定await语句.从文档中阅读

I do want to send it asyncronously but i dont care about the result, I mean I dont want to specify an await statement. I was about to try it whithout it when I read from documentation

如果异步方法未使用await运算符标记暂停点,则尽管使用了async修饰符,该方法仍将与同步方法一样执行.

If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier.

所以我会怀疑,是吗?有没有一种方法可以实现我想要的目标,或者这样做是一种不好的想法/想法.我希望我能表明自己的意思.谢谢

So mi doubt would be, is that so? is there a way to achieve what I am looking for or it is a bad pactice/idea thinking in doing something like that. I hope i made my self clear. Thanks

推荐答案

关于您在文档中阅读的内容,请这样考虑:

Regarding what you read in the docs, think about this this way:

public async Task OuterMethod()
{
    InnerMethod();
}

您已标记OuterMethod async ,但您没有等待任何操作.文档只是在说OuterMethod将同步运行,您也可以使用 void 而不是 async Task 对其进行标记.但是,OuterMethod同步运行的事实并不会改变InnerMethod的性质;它很可能是异步的,如果您不等待它,它将运行即忘即弃风格,很可能在后台线程上运行.

You've marked OuterMethod async, yet you're not doing any awaiting. The docs are simply saying that OuterMethod will run synchronously, and you may as well just mark it with void instead of async Task. However, the fact that OuterMethod runs synchronously doesn't change the nature of InnerMethod; it may well be asynchronous, and if you're not awaiting it, it will run fire-and-forget style, most likely on a background thread.

在您的特定情况下,InnerMethod将是发送电子邮件的方法.如果您确定自己不在乎发送电子邮件是成功还是失败,我建议您致电

In your specific case, InnerMethod would be the method that sends the email. If you're certain you don't care whether sending the email succeeds or fails, I'd suggest calling SmtpClient.SendAsync without awaiting.

这篇关于没有等待语句的C#异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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