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

本文翻译自:How to safely call an async method in C# without await

I have an async method which returns no data: 我有一个不返回任何数据的async方法:

public async Task MyAsyncMethod()
{
    // do some stuff async, don't return any data
}

I'm calling this from another method which returns some data: 我从另一个返回一些数据的方法中调用此方法:

public string GetStringData()
{
    MyAsyncMethod(); // this generates a warning and swallows exceptions
    return "hello world";
}

Calling MyAsyncMethod() without awaiting it causes a " Because this call is not awaited, the current method continues to run before the call is completed " warning in visual studio. MyAsyncMethod()调用MyAsyncMethod()而不等待它会导致“ 因为未等待此调用,因此当前方法将在调用完成之前继续运行 ”警告。 On the page for that warning it states: 在该警告的页面上,它指出:

You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions . 仅当您确定不想等待异步调用完成并且被调用的方法不会引发任何异常时 ,才应考虑禁止显示警告。

I'm sure I don't want to wait for the call to complete; 我确定我不想等待通话结束。 I don't need to or have the time to. 我不需要或没有时间。 But the call might raise exceptions. 但是通话可能会引发异常。

I've stumbled into this problem a few times and I'm sure it's a common problem which must have a common solution. 我已经几次遇到这个问题,并且我确定这是一个常见的问题,必须有一个通用的解决方案。

How do I safely call an async method without awaiting the result? 如何安全地调用异步方法而不等待结果ÿ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值