是否确定申报异步方法返回void沉默CS4014警告? [英] Is it OK to declare an async method as returning void to silence the CS4014 warning?
问题描述
Visual Studio中发出此code警告(因为这个呼叫没有等待,目前的方法执行之前完成呼叫继续')
Visual Studio emits a warning for this code ('because this call is not awaited, execution of the current method continues before the call is completed').
static void Main(string[] args)
{
FireAndForget(); // <-- Warning CS4014
// Do something else.
}
static async Task FireAndForget()
{
// Do something (cannot throw).
}
我的理解是,这是确定不等待任务在这个特殊的情况,因为FireAndForget绝不会抛出异常。
My understanding is that it is OK not to wait for the task in this particular case because FireAndForget will never throw an exception.
而不是用编译禁用警告,我正在考虑改变从任务FireAndForget的返回类型为void。这有效地沉默的编译器。
Instead of disabling the warning with a pragma, I was considering changing the return type of FireAndForget from Task to void. That effectively silences the compiler.
static async void FireAndForget() // <-- Task changed to void
{
// Do something (cannot throw).
}
不过,根据斯蒂芬·克利,异步无效的方法应尽量避免,所以我不太清楚该怎么做。
However, according to Stephen Cleary, 'async void' methods should be avoided so I am not quite sure what to do.
是否确定有一个'异步无效的方法,如果方法不设计成awaitable摆在首位,如果没有,会引发异常?
Is it OK to have a 'async void' method if the method is not designed to be awaitable in the first place and if no exception will be thrown?
推荐答案
这是的非常的难得有一个真正的发射后不管操作;即,操作,其中:
It's extremely rare to have a true fire-and-forget operation; that is, an operation where:
- 当它完成无人问津。
- 如果它完成无人问津。
- 如果它抛出一个异常,没有人问津。
特别地与最后的这些;大多数所谓的发射后不管作战实际上不是发射后不管,因为一些动作需要采取,如果它不会成功。
Particularly with the last of these; most so-called "fire-and-forget" operations are not actually fire-and-forget because some action needs to be taken if it doesn't succeed.
不过,也有少数情况下真正的发射后不管是适用的。
That said, there are a few situations where a true fire-and-forget is applicable.
我preFER使用异步任务
和分配任务到其他未使用的变量避免编译器警告:
I prefer to use async Task
and avoid the compiler warning by assigning the task to an otherwise unused variable:
var _ = FireAndForget();
异步任务
方法比异步无效
方法的可重用性和可测试性。
async Task
methods are more reusable and testable than async void
methods.
不过,我不会发脾气,如果只是用我的团队的开发人员异步无效
代替。
However, I wouldn't throw a fit if a developer on my team just used async void
instead.
这篇关于是否确定申报异步方法返回void沉默CS4014警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!