繁体   English   中英

在另一个线程的主线程中显示表单

[英]Show form in main thread from another thread

我用主要形式和显示进度的另一种形式开发多线程应用程序。 首先:我在MainForm中创建ProgressForm

Progress p=new Progress();

其次:我创建了Model类的新实例(包括我应用程序中的所有数据)。

Model m = new Model();

并订阅活动:

 m.OperationStarted += new EventHandler(OnCopyStarted);

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

第三:在另一个线程中运行某些操作,在该线程中更改另一个模型的属性

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

我的问题是:为什么进度表未显示在主线程中? 如何在没有锁定的情况下运行它?

试试吧 :

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

所有UI操作必须在主UI线程上运行。

在另一个线程上正在调用OnCopyStarted方法,因此在显示对话框之前,它必须先切换到UI线程。

您可以使用表单的BeginInvoke切换到UI线程。 如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM