2
當我取消並處置後臺工作人員時,儘管它已從VS線程列表中消失,但仍繼續向正在等待關閉的應用程序報告忙。此外,我的RunWorkerCompleted事件從未引發。儘管已經取消並且不再存在,但後臺工作人員報告仍處於忙狀態
調試顯示代碼已退出,沒有可看到的進一步掛起執行。
如果我刪除.IsBusy檢查,VS報告說,「這BackgroundWorker的正忙,不能同時運行多個任務」
我不明白爲什麼它不再VS列出的線程繼續收盤後操作。
private void UpdateTimeLine()
{
txtb_timeline.Text = "Updating...";
startTimelineUpdater.DoWork += new DoWorkEventHandler(startTimelineUpdater_DoWork);
startTimelineUpdater.RunWorkerAsync("hometimeline");
startTimelineUpdater.WorkerReportsProgress = true;
startTimelineUpdater.ProgressChanged += new ProgressChangedEventHandler
(startTimelineUpdater_ProgressChanged);
startTimelineUpdater.WorkerSupportsCancellation = true;
}
void startTimelineUpdater_DoWork(object sender, DoWorkEventArgs e)
{
//begin the thread to maintain updates of SQL
beginRegUpdateTimeline.DoWork += new DoWorkEventHandler(beginRegUpdateTimeline_DoWork);
beginRegUpdateTimeline.RunWorkerAsync();
beginRegUpdateTimeline.WorkerSupportsCancellation = true;
while (true)
{
List<string[]> sqlset;
Xtweet getSQL = new Xtweet();
if(e.Argument.ToString() == "hometimeline")
{
sqlset = getSQL.CollectLocalTimelineSql();
}
else
{
sqlset = getSQL.CollectLocalTimelineSql(Int64.Parse(e.Argument.ToString()));
}
int i = 0;
while (i < 10)
{
foreach (var stringse in sqlset)
{
StringBuilder sb = new StringBuilder();
sb.Append(stringse[0]);
sb.Append(": ");
sb.Append(stringse[1]);
sb.Append(" @ ");
sb.Append(stringse[2]);
sb.Append("\n");
BackgroundWorker bkgwk = sender as BackgroundWorker;
bkgwk.ReportProgress(0, sb.ToString());
Thread.Sleep(1000);
i++;
if(startTimelineUpdater.CancellationPending)
{
e.Cancel = true;
startTimelineUpdater.Dispose();
break;
}
}
if (e.Cancel == true)
{
break;
}
}
if (e.Cancel == true)
{
break;
}
}
}
/// <summary>
/// Handles the DoWork event of the beginRegUpdateTimeline control.
/// Updates the timeline sql on a regular basis
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
void beginRegUpdateTimeline_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
//update time in seconds
int secs = 10;
Xtweet.PreSqlDataCollection(null,null);
Thread.Sleep(secs*1000);
if(beginRegUpdateTimeline.CancellationPending)
{
e.Cancel = true;
beginRegUpdateTimeline.Dispose();
break;
}
}
}
private void startTimelineUpdater_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
txtb_timeline.Text = e.UserState.ToString();
}
我應該提到,這是WPF。我不認爲有一個DoEvents? – Damo 2012-04-08 13:18:09
沒關係,我添加了對Windows.Forms的引用,它工作得很好。 – Damo 2012-04-08 13:22:08
@Damo您應該考慮使用[Dispatcher](http://stackoverflow.com/a/4502200/884410)。 – 2012-04-08 13:25:37