我是 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# 新手,我无法将其转换为我想要的。
而且,我愿意接受建议,如果您发现我的代码效率低下或其他问题,我将很乐意接受您的建议。
谢谢你。