Ale*_*aie 0 .net c# azure ios async-await
我已按照本 教程为IOS应用程序创建推送通知中心.
当我运行代码
private static async void SendNotificationAsync()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(host, "sideview", false);
var alert = "{\"aps\":{\"alert\":\"Hello\"}}";
await hub.SendAppleNativeNotificationAsync(alert);
}
Run Code Online (Sandbox Code Playgroud)
来自控制台程序的静态void Main(string [] args),没有任何反应,控制台就停止了.
如果我使用
private static void SendNotificationAsync()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(host, "sideview", false);
var alert = "{\"aps\":{\"alert\":\"Hello\"}}";
hub.SendAppleNativeNotificationAsync(alert).Wait();
}
Run Code Online (Sandbox Code Playgroud)
每件事都很好
更新
正如Yuval Itzchakov在下面的答案中所说,控制台应用程序的主要方法无法标记为异步,因此不会等待异步方法
无法标记控制台应用程序的主要方法async.因此,您需要显式使用Task.Wait或Task.Result在异步操作上确保控制台main方法不会终止,从而关闭整个过程.
我假设电话是这样的:
public static void Main(string[] args)
{
// Do some stuff
SendNotificationAsync();
}
Run Code Online (Sandbox Code Playgroud)
你需要做两件事:
更改SendNotificationAsync到async Task的,而不是async void让你可以Wait在返回的任务.注意async void仅用于异步事件处理程序的兼容性:
private static async Task SendNotificationAsync()
{
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(host, "sideview", false);
var alert = "{\"aps\":{\"alert\":\"Hello\"}}";
await hub.SendAppleNativeNotificationAsync(alert);
}
Run Code Online (Sandbox Code Playgroud)Task.Wait在您的调用堆栈顶部使用:
public static void Main(string[] args)
{
// Do some stuff
SendNotificationAsync().Wait();
}
Run Code Online (Sandbox Code Playgroud)这将适用于控制台应用程序.对于具有默认以外的自定义的任何应用程序,不建议使用此方法.始终在这些类型的应用程序中一直使用.SynchronizationContextThreadPoolSynchronizationContextawait
| 归档时间: |
|
| 查看次数: |
2100 次 |
| 最近记录: |