我刚开始使用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.
更多推荐
发布评论