我想完全停止BackgroundWorker DoWork()過程,同時運行關閉窗體。如何停止Backgroundworker並關閉表單?
我已經應用了下面的代碼,但在「this.Invoke」中會引發錯誤:「調用或BeginInvoke無法在控件上調用,直到窗口句柄被創建。」同時形成關閉。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var dt_Images = db.Rings.Select(I => new { I.PaidRs, I.TypeID, I.RingID, I.CodeNo, Image = Image.FromStream(new MemoryStream(I.Image.ToArray())) }).OrderByDescending(r => r.TypeID);
foreach (var dr in dt_Images.ThenByDescending(r => r.RingID).ToList())
{
BTN = new Button();
BTN.TextImageRelation = TextImageRelation.TextAboveImage;
BTN.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
BTN.AutoSize = true;
BTN.Name = dr.RingID.ToString();
BTN.Image = dr.Image;
BTN.Text = dr.CodeNo.ToString() + " " + dr.TypeID.ToString();
this.Invoke(new MethodInvoker(delegate { if (backgroundWorker1 != null) flowLayoutPanel1.Controls.Add(BTN); else return; }));
BTN.Click += new EventHandler(this.pic_Click);
this.Invoke(new MethodInvoker(delegate { if (backgroundWorker1 == null) txt_pcs.Text = flowLayoutPanel1.Controls.Count.ToString(); else return;}));
}
}
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Escape)
{
backgroundWorker1.CancelAsync(); //backgroundworker doesnt stop here
backgroundWorker1 = null; //it still invokes the delegate
this.Dispose();
}
}
如何解決此錯誤?
請幫幫我。
爲什麼選擇的AutoResetEvent在backgroundWorker1。 CancelAsync()?有沒有好處?只是好奇。 – RvdK 2012-03-29 08:04:59
@PoweRoy:你說得對,第一部分也可以通過調用'CancelAsync'並在worker方法內輪詢'BackgorundWorker.CancellationPending'完成。這只是稍微更通用一些,並且在將簡單的後臺線程用作工作人員時可以工作。 – Groo 2012-03-29 08:08:30
使用此方法,但在此過程中「_workerStopped.WaitOne();」光標正在等待。 @Groo – Tulsi 2012-03-29 08:54:39