简体   繁体   中英

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?

Try it :

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

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()));
}

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