抑制“警告 CS4014:因为没有等待这个调用,当前方法的执行继续......"; [英] Suppressing "warning CS4014: Because this call is not awaited, execution of the current method continues..."

查看:37
本文介绍了抑制“警告 CS4014:因为没有等待这个调用,当前方法的执行继续......";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是 如何在不等待的情况下安全地调用 C# 中的异步方法".

如何很好地抑制以下警告?

警告 CS4014:由于不等待此调用,因此在调用完成之前会继续执行当前方法.考虑将await"运算符应用于调用结果.

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.

一个简单的例子:

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); 
}

我尝试过但不喜欢的:

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
    // ...
}

更新,由于原始接受的答案已被编辑,我已更改使用 C# 7.0 丢弃的答案,因为我认为 ContinueWith 不合适这里.每当我需要记录即发即忘操作的异常时,我都会使用更详细的方法Stephen Cleary 在这里提出的.

Updated, since the original accepted answer has been edited, I've changed the accepted answer to the one using C# 7.0 discards, as I don't think ContinueWith is appropriate here. Whenever I need to log exceptions for fire-and-forget operations, I use a more elaborate approach proposed by Stephen Cleary here.

推荐答案

借助 C# 7,您现在可以使用 丢弃:

With C# 7 you can now use discards:

_ = WorkAsync();

这篇关于抑制“警告 CS4014:因为没有等待这个调用,当前方法的执行继续......";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆