Windows MessageBox Display Issue with Cross Thread

680 Views Asked by At

I am trying to display error message notification using MessageBox.Show() method. But I am getting Cross thread operation issue. I used the below code. How can I resolve the cross thread issue? I tried with MethodInvoker but it is not solving my issue. Kindly suggest me the guidelines to resolve this issue.

 public static class Notification()
 {

   public static void ShowErrorMessage(IWin32Window owner, String msg)
   {
       MessageBox.Show(owner, msg, Caption+ " - " + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

}

Issue :

Cross-thread operation not valid:Control 'MainPage' accessed from a thread other than the thread it was created on.

2

There are 2 best solutions below

0
On

It seems there is an answer here MessageBox.show() is it not safe to call in worker thread? , though the question is a bit misleading.

Also, this Microsoft documentation page explains in detail how to make thread-safe calls to WinForm controls, and provides you with code examples.

7
On

Here is a full example of calling a MessageBox from another thread. The trick here is to stash the dispatcher somewhere (like a static variable in some other static class -- in this example, I put the static variable in the same class, but you could put it anywhere) And then you ask the Dispatcher to Invoke some call on the main thread. You can do this synchronously (Invoke) or asynchronously (BeginInvoke) to suit your needs.

static System.Windows.Threading.Dispatcher d; // Save the dispatcher in this global

private void Form1_Load(object sender, EventArgs e)
{
    d = System.Windows.Threading.Dispatcher.CurrentDispatcher;
    System.Threading.Timer t = new System.Threading.Timer((obj) => {
        d.Invoke(() => {
            MessageBox.Show("hi!");
        });
    }, null, 1000, System.Threading.Timeout.Infinite);

}