我的後臺工作人員遇到了很多麻煩。我有一個後臺工作人員上傳圖片(有時超過100)到tumblr。自然,這是非常重複的。
我的問題是這樣的:
1)儘快或之後,我開始我的線程幾秒鐘,backgroundWorker1_RunWorkerCompleted
叫,如通過其打印該方法/事件中的文本。
2)當我取消線程時,它會調用backgroundWorker1_RunWorkerCompleted
,如打印其中的文本所示,但是,文件會繼續保持上傳。看起來線程仍然存在。
我不知道我做錯了什麼,我一直在尋找過去的幾天,並嘗試了很多不同的方法。這裏是我的代碼:
backgroundWorker一開始就退出,再加上取消後繼續
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker backgroundWorker = sender as BackgroundWorker;
var restClient = new RestClient("http://tumblr.com/api/write");
foreach (string item in queueBox.Items)
{
if (!backgroundWorker.CancellationPending)
{
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("email", usernameBox.Text);
request.AddParameter("password", passwordBox.Text);
request.AddParameter("type", "photo");
byte[] byteArray = File.ReadAllBytes(FolderName + "\\" + item);
request.AddFile("data", byteArray, FolderName + "\\" + item);
var newItemToAvoidClosure = item;
restClient.ExecuteAsync(request, response => { doneBox.Invoke(new UpdateTextCallback(this.UpdateText), new object[] { newItemToAvoidClosure }); });
}
else
{
e.Cancel = true;
}
}
}
這是我的RunWorkerCompleted
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!(e.Cancelled))
{ //if not cancelled
if (!(e.Error == null))
{ //if above true, see if theres an error
doneBox.Items.Add("\r\nAn Error Ocurred: " + e.Error.Message + "\r\n. However, what you uploaded may have been successful up until this error.");
}
else
{ //else there is no error which means it was 100% successful
doneBox.Items.Add("Finished uploading! Go and check out your stuff on Tumblr! ^_^");
}
}
else //else the user DID press cancel
{
doneBox.Items.Add("You pressed Cancel - However, the photos before you pressed cancel have been uploaded.");
}
}
現在,我會盡量解釋什麼,我想在我DoWork
正在發生的事情,
由於對循環是循環每張照片上傳的內容,if語句在那裏,因此它可以不斷檢查取消懸置是否爲真。如果是,請將e.Cancel設置爲true以結束該線程。
此外,我使用ExecuteAsync上傳,所以我希望我能夠終止線程中上載,以便照片不上傳。
好的,我很抱歉,我知道這已經被討論過。我只是無法弄清楚我做錯了什麼。
順便說一句,這是我試圖取消:
public void stopButton_Click(object sender, EventArgs e)
{
doneBox.Items.Add("You pressed the stop button.");
backgroundWorker1.CancelAsync();
}
謝謝大家。
只要您使用ExecuteAsync(),您對BackgroundWorker就沒有用處。使用Execute(),這樣可以實際取消。 – 2012-03-24 14:30:25