没有await语句的c#异步任务(c# async task with no await statement)

编程入门 行业动态 更新时间:2024-10-17 19:24:42
没有await语句的c#异步任务(c# async task with no await statement)

我刚开始使用c#开发,而且我总是遇到异步编程,我对异步执行任务有疑问。

我有自己的服务能够发送电子邮件(不详细但它的工作)我希望该方法的执行异步运行,我一直在阅读关于异步和等待的msdn文档。

我确实想发送它异步但我不关心结果,我的意思是我不想指定await语句。 当我从文档中读到时,我正打算尝试它

如果异步方法不使用await运算符来标记挂起点,则该方法将作为同步方法执行,尽管存在异步修饰符。

所以mi怀疑是这样的吗? 有没有办法实现我正在寻找的东西,或者这是一个糟糕的做法/想法做这样的事情。 我希望我清楚自己。 谢谢

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

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.

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

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

最满意答案

关于你在文档中读到的内容,请考虑这种方式:

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

你已经将OuterMethod标记为async ,但你没有做任何等待。 文档只是说OuterMethod将同步运行,你也可以用void而不是async Task来标记它。 然而,OuterMethod同步运行的事实并没有改变InnerMethod的本质; 它可能是异步的,如果你没有等待它,它将运行即发即弃的风格,很可能是在后台线程上。

在您的特定情况下,InnerMethod将是发送电子邮件的方法。 如果您确定不关心发送电子邮件是成功还是失败,我建议您在不等待的情况下调用SmtpClient.SendAsync 。

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

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

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.

更多推荐

本文发布于:2023-07-04 17:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   await   async   statement   task

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!