如何使用线程在C#中的一次发送多个Web请求? [英] How can you use threading to send multiple web requests at a time in c#?
问题描述
我有一个简单的ASP.NET的小程序,和我想要学习基本的多线程处理,使其运行更加平稳。
I have a simple ASP.NET applet, and I'm trying to learn basic multithreading to make it run more smoothly.
让我们说我有挂在下面的方法的一个按钮:
Let's say I have a button hooked up to the following method:
private NlSearch search;
protected void SearchButtonClick(object sender, EventArgs e)
{
int resultCount = search.MakeRequests(SearchForm.Text);
resultsLabel.Text += SearchForm.Text + ": " + resultCount.ToString() + " occurances";
}
所有MakeRequests确实是一个问题,POST请求上做一个第三方网站上搜索和抓取从响应的结果数。然后用结果数沿检索词被添加到页面。
All MakeRequests does is issue a POST request to do a search on a 3rd party website and grabs the number of results from the response. The search term along with the number of results is then added to the page.
但是,如果我是做类似提交新的搜索第一个搜索回应之前,它只会中断原来的搜索,只有最近的搜索将它写的结果的标签。
However if I were to do something like submit a new search before the first search has responded, it will simply interrupt the original search and only the most recent search will write it's results to the label.
据我了解有办法用C#线程要做到这一点,但我无法弄清楚如何正确使用任务做到这一点。我试图把方法的身体变成不带任何参数,我再用于创建和运行任务的第二个方法,但让我觉得我是用不正确的任务,这并没有改变行为。
I understand there's a way to do this with C# threading, but I can't figure out how to use tasks correctly to do this. I tried putting the body of the method into a second method with no arguments that I then used to create and run a task, but this did not change the behavior so I think I was using tasks incorrectly.
任何帮助或建议将AP preciated,谢谢。
Any help or advice would be appreciated, thanks.
编辑:我试过到目前为止:两个答案似乎是工作在检索值,但由于某种原因,没有真正将它们添加到标签的某些原因。例如:
What I've tried so far: both answers seemed to 'work' at retrieving values but for some reason neither actually added them to the label for some reason. For example
protected void NewSearchClick(object sender, EventArgs e)
{
new Thread(() => MakeRequest(SearchForm.Text)).Start();
}
和
protected void MakeRequest(string text)
{
int resultCount = search.MakeRequests(text);
if (resultsLabel != null) resultsLabel.Text += text + ": " + resultCount + " occurances";
}
似乎检索值但标签不改变
seemed to retrieve the value but the label does not change.
推荐答案
在一个WPF应用程序,你应该使用两个线程与调度员,因为只有UI线程可以写入标签。更具体地讲,你应该使用调度员作为回调的UI进行任何更新时,任务完成:
In a WPF app, you should use both threads and Dispatcher, because only the UI thread can write to a label. More specifically, you should use the dispatcher as a callback to update anything in the UI when a task is complete:
protected void SearchButtonClick(object sender, EventArgs e)
{
new Thread(() => MakeRequest(SearchForm.Text)).Start();
}
protected void MakeRequest(string text)
{
int resultCount = search.MakeRequests(text);
// tell UI thread to update label
Dispatcher.BeginInvoke(new Action(() =>
{
resultsLabel.Text += text + ": " + resultCount + " occurances";
}));
}
EDIT1:使用调度不仅仅是线程
EDIT2:同时使用调度和线程
这篇关于如何使用线程在C#中的一次发送多个Web请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!