我有一个用于发送通知目的的异步方法.但是我在调用该方法时未设置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 } }然后调用它.
更多推荐
异步/等待方法
发布评论