tags:

views:

1007

answers:

4

Say I have a thread that keeps running in the background to figure if a URL is accessible. If the URL is not accessible, the application need to show a modal dialog box. Things cannot go on if the URL is down. If I simply do a MessageBox.show from inside the thread, that message box will not be modal. ShowDialog won't work either.

+3  A: 

You may want to use Control.Invoke (or this.Invoke)

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
      this.Invoke(new MessageBoxDelegate(ShowMessage), "Title", "MEssage", MessageBoxButtons.OK, MessageBoxIcon.Information);    }

That will make it modal to the UI thread.

Otávio Décio
A: 

You could try creating an event that fires from the background thread. Have the main form listen for the event in which case it would fire off the messagebox in modal form. Though I like the approach suggested by ocdecio better.

Jason Down
+1  A: 
public class FooForm : Form {

    public static void Main() {
        Application.Run(new FooForm());
    }

    public FooForm() {
        new Thread(new Action(delegate {
            Invoke(new Action(delegate {
                MessageBox.Show("FooMessage");
            }));
        })).Start();
    }

}

This program creates a form window, and immediately creates another non-gui thread which wants to pop up a modal dialog window on the form's gui thread. The form's Invoke method takes a delegate and invokes that delegate on the form's gui thread.

Justice
+1  A: 

Thanks everyone. I solved the problem this way:

The thread:

private Thread tCheckURL;

// ...

tCheckURL = new Thread(delegate()
{
    while (true)
    {
        if (CheckUrl("http://www.yahoo.com") == false)
        {
            form1.Invoke(form1.myDelegate);
        }
    }
});
tCheckURL.Start();

Inside Form1:

public delegate void AddListItem();
public AddListItem myDelegate;

Form1()
{
    //...
    myDelegate = new AddListItem(ShowURLError);
}
public void ShowURLError()
{
    MessageBox.Show("The site is down");
}

Not sure if this is the shortest way to do it.. but it gets the job down.