【发布时间】:2024-01-23 19:35:01
【问题描述】:
我是 C#、RestSharp 和线程的新手,所以这就是我想要做的事情:
我已经制作了一个程序,可以让我将照片上传到 tumblr,到目前为止,我已经完成了上传工作。现在我需要停止按钮才能工作,我相信这意味着我必须使用ExecuteAsync() 而不是Execute()。
我还将我的代码放入了后台工作程序中,如下所示:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
MessageBox.Show("You pressed Cancel.");
}
else
{
var restClient = new RestClient("http://tumblr.com/api/write");
foreach (string item in queueBox.Items)
{
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json; //I don't know if this line is necessary
request.AddParameter("email", usernameBox.Text);
request.AddParameter("password", passwordBox.Text);
request.AddParameter("type", "photo");
request.AddFile("data", FolderName + "\\" + item);
RestResponse response = restClient.Execute(request);
doneBox.Invoke(new UpdateTextCallback(this.UpdateText),
new object[] { item });
}
}
}
我相信我已经正确设置了它。当我按upload 时,它会相应地转到else。但是,我认为 RestResponse response = restClient.Execute(request); 这是阻塞的,这不允许我的代码继续检查标志。
这就是我尝试取消它的方式。
public void stopButton_Click(object sender, EventArgs e)
{
doneBox.Items.Add("You pressed the stop button.");
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.CancelAsync();
}
另外,如果这是相关的,我有:
public delegate void UpdateTextCallback(string item); 允许我调用UpdateText 和FinishedText,如上图backgroundWorker1_DoWork 所示。
对于我的问题,在这种情况下如何使用 ExecuteAsync?我已经搜索过,但找不到任何对我有帮助的东西,我找不到与我的代码类似的示例,而且由于我是 c# 新手,我无法将其转换为我想要的。
而且,我愿意接受建议,如果您发现我的代码效率低下或其他问题,我将很乐意接受您的建议。
谢谢。
【问题讨论】:
-
您在 DoWork 的开始看到取消的几率为零。在循环内移动测试。可能已经足够好了。
标签: c# backgroundworker blocking kill restsharp