[英]How can you use threading to send multiple web requests at a time in c#?
我有一個簡單的ASP.NET小程序,我正在嘗試學習基本的多線程以使其運行更順暢。
假設我有一個連接到以下方法的按鈕:
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請求以在第三方網站上進行搜索,並從響應中獲取結果數。 然后將搜索項和結果數添加到頁面中。
但是,如果我在第一次搜索響應之前做了類似提交新搜索的操作,它只會中斷原始搜索,只有最近的搜索會將結果寫入標簽。
我知道有一種方法可以用C#線程來做到這一點,但我無法弄清楚如何正確使用任務來做到這一點。 我嘗試將方法的主體放入第二個方法,沒有參數,然后我用來創建和運行任務,但這並沒有改變行為,所以我認為我使用的任務不正確。
任何幫助或建議將不勝感激,謝謝。
編輯:我到目前為止所嘗試的內容:兩個答案在檢索值時似乎“有效”,但出於某種原因,由於某種原因,它們實際上都沒有將它們添加到標簽中。 例如
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";
}
似乎檢索了價值,但標簽沒有改變。
在WPF應用程序中,您應該同時使用線程和Dispatcher,因為只有UI線程可以寫入標簽。 更具體地說,您應該使用調度程序作為回調來在任務完成時更新UI中的任何內容:
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:使用Dispatcher而不僅僅是線程
Edit2:同時使用Dispatcher和線程
我會使用.NET Task來管理線程池。
鏈接: 任務[托管並行]
protected void SearchButtonClick(object sender, EventArgs e)
{
var text = SearchForm.Text;
Task.Factory.StartNew(() =>
{
var resultCount = search.MakeRequests(text);
resultsLabel.Text += text + ": " + resultCount + " occurances";
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.