我正在尝试创建一个ProgressBar表单,该表单使用BackgroundWorker在显示进度条的同时在不同的线程上执行操作。
目前,我的ProgressBar类包含一个ProgressBarControl,下面是代码的样子:
public partial class QTProgressBar : DevExpress.XtraEditors.XtraForm
{
private BackgroundWorker m_backgroundWorker;
private AutoResetEvent m_resetEvent;
public QTProgressBar()
{
InitializeComponent();
InitializeProgressBar();
m_backgroundWorker = new BackgroundWorker();
m_backgroundWorker.WorkerReportsProgress = true;
m_backgroundWorker.WorkerSupportsCancellation = true;
m_backgroundWorker.DoWork += new DoWorkEventHandler(m_backgroundWorker_DoWork);
m_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(m_backgroundWorker_ProgressChanged);
m_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_backgroundWorker_RunWorkerCompleted);
m_resetEvent = new AutoResetEvent(false);
}
void m_backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
m_resetEvent.Reset();
CloseProgressBar();
}
void CloseProgressBar()
{
if (InvokeRequired)
{
Invoke( new MethodInvoker(CloseProgressBar));
return;
}
this.Close();
}
void m_backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Action operation = e.Argument as Action;
operation();
}
public void StartAsyncTask(Action operation)
{
m_resetEvent.Set();
m_backgroundWorker.RunWorkerAsync(operation);
}
}
现在,当我想要显示弹出窗口时,我会这样做:
QTProgressBar op = new QTProgressBar();
op.StartAsyncTask(() => LongDurationOperation(5, 5));
op.ShowDialog(); // i would like to move this inside the ProgressBar class.
//Thread gets blocked here until operation finishes.
LongDurationOperation在哪里:
public void LongDurationOperation(int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Thread.Sleep(100);
}
}
}
我想避免阻塞任何调用
的线程ShowDialog()
progressBar类的方法。 如果我在ProgressBar类中移动它,则线程被阻塞并且操作不会执行。
是否可以避免阻塞调用Showdialog()方法的线程?
另外,你能给我一些关于如何改进这门课程的提示吗?
非常感谢。
答案 0 :(得分:6)
表单中存在两种不同的调用:
myForm.ShowDialog();
是阻止调用它的线程的模态版本。它用于弹出窗口,必须阻止其他操作发生(如保存对话框)。
myForm.Show(IWin32Window owner);
是非模态版本。它不会阻止当前线程,但不会返回任何结果。但是,您必须将其传递给所有者,通常是这样的:
myForm.Show(this);