且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用线程在C#中的一次发送多个Web请求?

更新时间:2022-12-26 18:31:30

在一个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:同时使用调度和线程