异步/等待方法-无需等待方法执行 [英] Async / Await method - No need to wait for method execution

查看:87
本文介绍了异步/等待方法-无需等待方法执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于发送通知目的的异步方法.但是我在调​​用该方法时未设置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
     }
}

然后调用它.

这篇关于异步/等待方法-无需等待方法执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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