燮pressing"警告CS4014:因为这个呼叫没有等待,目前的方法继续执行..." [英] Suppressing "warning CS4014: Because this call is not awaited, execution of the current method continues..."
问题描述
这是不是<一个副本href=\"http://stackoverflow.com/questions/15522900/how-to-safely-call-an-async-method-in-c-sharp-without-await\">\"How安全地调用在C#异步方法,无需等待。
我如何很好地燮preSS以下警告?
警告CS4014:因为这个呼叫没有等待,呼叫结束之前,在当前的方法继续执行。考虑应用'等待'操作的调用的结果。
块引用>一个简单的例子:
静态异步任务WorkAsync()
{
等待Task.Delay(1000);
Console.WriteLine(完成!);
}静态异步任务StartWorkAsync()
{
WorkAsync(); //我要射后不理 //更无关异步/这里等待的东西,例如:
// ...
等待Task.Delay(2000);
}我试过,不喜欢:
静态异步任务StartWorkAsync()
{
#pragma警告禁用4014
WorkAsync(); //我想在这里发射后不管
的#pragma警告恢复4014
// ...
}静态异步任务StartWorkAsync()
{
变种ignoreMe = WorkAsync(); //我想在这里发射后不管
// ...
}
解决方案您可以创建一个扩展方法,将prevent警告。扩展方法可以是空的,或者你可以添加异常处理
.ContinueWith()
那里。静态类TaskExtensions
{
公共静态无效忘了(这个任务任务)
{
}
}公共异步任务StartWorkAsync()
{
this.WorkAsync()忘了()。
}This is not a duplicate of "How to safely call an async method in C# without await".
How do I nicely suppress the following warning?
warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
A simple example:
static async Task WorkAsync() { await Task.Delay(1000); Console.WriteLine("Done!"); } static async Task StartWorkAsync() { WorkAsync(); // I want fire-and-forget // more unrelated async/await stuff here, e.g.: // ... await Task.Delay(2000); }
What I tried and did not like:
static async Task StartWorkAsync() { #pragma warning disable 4014 WorkAsync(); // I want fire-and-forget here #pragma warning restore 4014 // ... } static async Task StartWorkAsync() { var ignoreMe = WorkAsync(); // I want fire-and-forget here // ... }
解决方案You can create an extension method that will prevent the warning. The extension method can be empty or you can add exception handling with
.ContinueWith()
there.static class TaskExtensions { public static void Forget(this Task task) { } } public async Task StartWorkAsync() { this.WorkAsync().Forget(); }
这篇关于燮pressing&QUOT;警告CS4014:因为这个呼叫没有等待,目前的方法继续执行...&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!