2
我試圖創建一個使用BackgroundWorker到在不同的線程執行相應的操作,同時顯示進度條的進度表。顯示形式(對話),而不會阻塞當前線程(進度例子)
在我的進度條類包含一個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);
}
}
}
我想,以避免阻塞調用日任何線程e
ShowDialog()
progressBar類的方法。 如果我搬到了ProgressBar類線程內任何地方這遭到封鎖和操作不執行。
是否possbile以避免阻塞調用的ShowDialog()方法的線程?
而且,你能給我這個類怎麼能提高一些提示?
非常感謝。
Tbanks爲答案。從我看到this.Handle返回一個IntPtr和Show(this.Handle)生成一個編譯器錯誤。 –
@DanDinu:哦,哇......我在工作上睡覺。對不起,我編輯了我的帖子。它是'Show(this)'而不是Show(this.Handle)'這個''this'是一個有效的'Form'。 – LightStriker
還有顯示()沒有指定的所有者,這是相同的設置可見=真。 https://msdn.microsoft.com/de-de/library/system.windows.forms.form.show%28v=vs.110%29.aspx – Echsecutor