简体   繁体   English

C# Fire and Forget 任务并丢弃

[英]C# Fire and Forget Task and discard

I need to do a fire and forget call to some async method.我需要生火并忘记调用一些异步方法。 I realised VS is suggesting that I can set the call to a _discard and the IDE warning goes away.我意识到 VS 建议我可以将调用设置为 _discard 并且 IDE 警告消失。 But I'm not sure if that call is still not awaited when used with the discard.但是我不确定当与丢弃一起使用时是否仍然没有等待该调用。 Would it be?可不可能是?

 public async Task<object> SomeSideTaskToBeForgotten()
 {
     ...blah blah
 }

 public async Task MainTask()
 {
     ..some stuff
     _ = SomeSideTaskToBeForgotten(); //is this still fire and forget?
     ..some other stuff
 }

Yes, it's still fire and forget.是的,它仍然是火和忘记。

When SomeSideTaskToBeForgotten();SomeSideTaskToBeForgotten(); returns a Task , the remainder of your method will execute, without waiting for the Task to complete.返回一个Task ,您的方法的其余部分将执行,而无需等待Task完成。

The discard just makes explicit the fact that the Task isn't required for any further processing.丢弃只是明确说明了Task不需要任何进一步处理的事实。

VS will be recommending the discard because SomeSideTaskToBeForgotten(); VS 会推荐丢弃,因为SomeSideTaskToBeForgotten(); returns something ie not void.返回一些东西,即不无效。

Or you could just call it like the following and pragma out the warnings if you need. 或者,您可以像下面这样调用它,并在需要时发出警告。

SomeSideTaskToBeForgotten();

Just a side note : nothing suggested here (no unobserved task) is truly fire and forget until you catch your exceptions inside of SomeSideTaskToBeForgotten . 附带说明 :此处没有建议(没有观察到的任务)是真正引起火灾并忘记的事情直到您在SomeSideTaskToBeForgotten内部捕获异常SomeSideTaskToBeForgotten The reason why is, if an exception is thrown on an unobserved task, the error is placed on the task and can be rethrown at unexpected times. 原因是,如果在未观察到的任务上引发了异常,则该错误将被放置在任务上,并且可以在意外的时间重新抛出。 You wont be forgetting it as its likely to exception you out of your application. 您不会忘记它,因为它很可能使您脱离应用程序。 Just saying :) 只是说:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM