Search code examples
c#windows-phone-8push-notificationwindows-phonempns

Getting exception when creating HttpNotificationChannel, but works correctly when debugging step-by-step


I use the following code to create a push notification channel.

The problem is that when I execute the code, most of the times (not always), this function throws System.NullReferenceException. However, if I set a breakpoint and debug it step by step, it works correctly and returns valid HttpNotificationChannel.

private string AcquirePushChannel()
{
    HttpNotificationChannel currentChannel =  HttpNotificationChannel.Find("MyPushChannel");

    if (currentChannel == null)
    {
        currentChannel = new HttpNotificationChannel("MyPushChannel");
        currentChannel.Open();
        currentChannel.BindToShellTile();
        currentChannel.BindToShellToast();
    }

    currentChannel.ChannelUriUpdated += (s, e) =>
    {
        // Code here
    };
    currentChannel.ShellToastNotificationReceived += async (s, e) =>
    {
        // Code here
    };

    return currentChannel.ChannelUri.AbsoluteUri;
}

Since when debugging step by step it works correctly, I'm not able to find the problem. Any idea?


Solution

  • The problem is that opening a channel is an asynchronous operation. That is the reason there is a ChannelUriUpdated event. There is no way to return the ChannelUri from your function, because it may not be available at the end of this function. It will become available in this block

    currentChannel.ChannelUriUpdated += (s, e) =>
    {
        // here the channel uri is available as e.ChannelUri
    };
    

    The reason it works for you when debugging is that the event gets fired before you step to the last line.