异步/等待方法

编程入门 行业动态 更新时间:2024-10-23 23:25:26
本文介绍了异步/等待方法-无需等待方法执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用于发送通知目的的异步方法.但是我在调​​用该方法时未设置await关键字.因为不需要等待对我的回复.

I have a async method for Send notification purpose. but i am not set await keyword while invoking the method. because no need to wait for the response to me.

但是,它说,警告.

是否需要添加await关键字来解决警告或将其忽略?

Whether need to add await keyword to solve the Warning or ignore it?

推荐答案

如果可以使用C#7功能,请将其分配给"discard"变量:

If you can use C# 7 features, assign it to "discard" variable:

_ = iPushNotificationService.SendPushNotification(objNotificationMessage);

如果您不能使用C#7,则可以将其分配给某个变量:

If you can't use C# 7 - you can just assign it to some variable:

var t = iPushNotificationService.SendPushNotification(objNotificationMessage);

或使用如下扩展方法:

public static class TaskExtensions { public static void Ignore(this Task t) { } }

然后:

iPushNotificationService.SendPushNotification(objNotificationMessage).Ignore();

请注意,您可能对结果不感兴趣,但是如果它未能发送该通知(至少记录该通知),您可能会感兴趣.在这种情况下,您可以使用 ContinueWith :

Note that you might be not interested in result, but you might be interested if it fails to send that notification, at least to log that. In that case you can either use ContinueWith:

SendNotification().ContinueWith(c => { // do something with c.Exception }, TaskContinuationOptions.OnlyOnFaulted).Ignore();

或将其移动到单独的异步方法:

Or move that to separate async method:

static async void SendNotification() { // if you hate async void - use Task try { await iPushNotificationService.SendPushNotification(objNotificationMessage); } catch (Exception ex { // log it } }

然后调用它.

更多推荐

异步/等待方法

本文发布于:2023-11-10 02:16:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574064.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!