Mikhail Sokolov
Mikhail Sokolov

Reputation: 556

Show form in main thread from another thread

I developing multithreading application with main form and another form in which progress is shown. At first: I create ProgressForm in MainForm

Progress p=new Progress();

Second: I create new instance of class Model (whith all data in my app).

Model m = new Model();

And subscribe for event:

 m.OperationStarted += new EventHandler(OnCopyStarted);

private void OnCopyStarted(object sender, EventArgs e)
{
  p.Show();
}

Third: I run some operation in another thread where I change property in another Model

 private bool isStarted;
            public bool IsStarted
            {
                get{return isStarted;}
                set 
                {
                    isStarted = value;
                    if (isStarted && OperationStarted != null)
                    { 
                        OperationStarted(this, EventArgs.Empty);
                    }
                }
            }

My questoin is: Why Progress form is show not in Main Thread? How can I run it without lockups?

Upvotes: 1

Views: 2056

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

All UI operations must run on the main UI thread.

The OnCopyStarted method is being called on another thread, so it must switch to the UI thread before before showing the dialog.

You can use your form's BeginInvoke to switch to the UI thread. Such as:

void OnCopyStarted(object sender, EventArgs e)
{
   p.BeginInvoke((Action) (() => p.Show()));
}

Upvotes: 3

user1711092
user1711092

Reputation:

Try it :

var t = new Thread(() => {
            Application.Run(new Progress ());
        });
t.Start();

Upvotes: 2

Related Questions