我有一个类似于下面的ASP.NET MVC Controller方法:
public JsonResult GenerateNotifications()
{
Task.Factory.StartNew(() => MyService.GenerateNotifications());
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
我的服务方法如下所示:
public async void GenerateNotifications()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(AppHelper.AzureNotificationHubConnectionString, "myhub");
for (int i = 0; i < 10; i++)
{
var notification = new
{
aps = new
{
alert = string.Format("Awesome Notification {0}", i),
sound = "default"
}
};
string notificationJSON = JsonConvert.SerializeObject(notification);
NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(notificationJSON, "mytag");
}
}
我遇到的问题是,我应该收到的10个通知中,我通常只收到5-6个通知。
我处理async
电话的方式有问题吗?
我是否应该以与控制器不同的方式生成通知?
答案 0 :(得分:2)
由于GenerateNotification
方法为async void
,您可能会收到一些被吞下的异常。您应该返回Task
并确保await
方法,以便观察和重新抛出异常。
完成后,您可以Task.Factory.StartNew(() => MyService.GenerateNotifications())
而不是await MyService.GenerateNotifications()
。有关使用async/await
我会将您的代码更改为:
public async Task<JsonResult> GenerateNotifications()
{
await MyService.GenerateNotifications();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
public async Task GenerateNotifications()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(AppHelper.AzureNotificationHubConnectionString, "myhub");
for (int i = 0; i < 10; i++)
{
var notification = new
{
aps = new
{
alert = string.Format("Awesome Notification {0}", i),
sound = "default"
}
};
string notificationJSON = JsonConvert.SerializeObject(notification);
NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(notificationJSON, "mytag");
}
}
目前,您还会连续发送通知。您可以将生成的任务添加到列表中,然后使用await Task.WhenAll
await
完成它们,将它们并行发送出来。
public async Task GenerateNotifications()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(AppHelper.AzureNotificationHubConnectionString, "myhub");
List<Task<NotificationOutcome>> notificaitonTasks = new List<Task<NotificationOutcome>>();
for (int i = 0; i < 10; i++)
{
var notification = new
{
aps = new
{
alert = string.Format("Awesome Notification {0}", i),
sound = "default"
}
};
string notificationJSON = JsonConvert.SerializeObject(notification);
notificaitonTasks.Add(hub.SendAppleNativeNotificationAsync(notificationJSON, "mytag"));
}
await Task.WhenAll(notificaitonTasks);
}