Search code examples
c#wpfmessagebox

How to avoid multiple messageboxes continuous display?


I have a problem with WPF MessageBox,its due to when internet connection is not available. I need the message to displays once only, but it shows multiple times.

 private void Application_Startup(object sender, StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(cc);
    }
    void cc(object sender, UnhandledExceptionEventArgs e)
    {
        Exception ex = e.ExceptionObject as Exception;
        MessageBox.Show(ex.Message, "Uncaught", MessageBoxButton.OK);
    }

Solution

  • Simple.
    You should confirm before you show message box.

    // message box flag.
    bool canIShowMessageBox = true;
    
    // for thread lock.
    object exLocker = new object();    
    
    void cc(object sender, UnhandledExceptionEventArgs e)
    {
       lock(exLocker)
       {
          if (canIShowMessageBox)
             canIShowMessageBox = false;
          else
             return;
       }
       Exception ex = e.ExceptionObject as Exception;
       MessageBox.Show(ex.Message, "Uncaught", MessageBoxButton.OK);
    
       lock(exLocker)
          canIShowMessageBox = true;
    }