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

标签 c# .net multithreading

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

Progress p=new Progress();

其次:我创建了Model类的新实例(这是我应用程序中的所有数据)。
Model m = new Model();

并订阅 Activity :
 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);
                    }
                }
            }

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

最佳答案

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

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

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

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

关于c# - 在另一个线程的主线程中显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244955/

相关文章:

c# - OVER 子句中的 SQL ORDER BY 与 CLR 聚合不兼容?

.net - 如何获取.net中ForeignSecurityPrincipals对象的详细信息

java - 将 tryLock() 与 wait() 和 notify()/notifyAll() 一起使用

java - 在此调用 'wait' 和 'notify'

c# - 无法在 Azure Function 中加载证书

c# - 可变范围抽象

java - 通过udp传输文件

c# - .NET/C#中swagger json规范到静态html文件的转换

c# - 旧的 App_Web.xxxx.dll 会影响站点行为吗?

c - M 次执行后在 C 中完成多线程程序?