我用主要形式和显示进度的另一种形式开发多线程应用程序。
首先:我在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/