Azure通知中心.net api无法正常工作

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在下面的答案中所说,控制台应用程序的主要方法无法标记为异步,因此不会等待异步方法

Yuv*_*kov 5

无法标记控制台应用程序的主要方法async.因此,您需要显式使用Task.WaitTask.Result在异步操作上确保控制台main方法不会终止,从而关闭整个过程.

我假设电话是这样的:

public static void Main(string[] args)
{
    // Do some stuff
    SendNotificationAsync();
}
Run Code Online (Sandbox Code Playgroud)

你需要做两件事:

  1. 更改SendNotificationAsyncasync 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)
  2. Task.Wait在您的调用堆栈顶部使用:

    public static void Main(string[] args)
    {
       // Do some stuff
       SendNotificationAsync().Wait();
    }
    
    Run Code Online (Sandbox Code Playgroud)

这将适用于控制台应用程序.对于具有默认以外的自定义的任何应用程序,建议使用此方法.始终在这些类型的应用程序中一直使用.SynchronizationContextThreadPoolSynchronizationContextawait