简体   繁体   中英

MessageDialog crashes when called - Windows Phone Store app

I am having a message dialog to prompt the user when there is no internet.

public async void validateInternet()
{
    if (!isInternet())
    {
        Action cmdAction = null;
        MessageDialog _connectAlert = new MessageDialog("We are currently experiencing difficulties with your conectivity. Connect to internet and refresh again.", "No internet");
        _connectAlert.Commands.Add(new UICommand("Retry", (x) => { cmdAction = () => validateInternet(); }));
        _connectAlert.DefaultCommandIndex = 0;
        _connectAlert.CancelCommandIndex = 1;
        await _connectAlert.ShowAsync();
        cmdAction.Invoke();
    }
}

public static bool isInternet()
{
    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
    return internet;
}

Now, I call this function validateInternet when MainPage has loaded. The app opens the message dialog, and crashes immediately. What's wrong with the code?

A A first chance exception of type 'System.UnauthorizedAccessException' occurred in BusTrack.exe Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) A first chance exception of type 'System.UnauthorizedAccessException' occurred in BusTrack.exe Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) is thrown at

await _connectAlert.ShowAsync();

As @yasen rightly pointed out, the validateInternet() was called both in MainPage_loaded() and OnNavigatedTo() .

Hence, System.UnauthorizedAccessException occurs since both of those methods will try to show a messageDialog . So, never try to call two message dialogs at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM