我正在尝试创建一个 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() 方法的线程?
另外,你能给我一些关于如何改进这门课的提示吗?
非常感谢。