我的應用程序通常使用WebRequest從網頁中獲取數據,但在獲取數據時不可能點擊按鈕等。我明白我必須使用線程/背景工作,但我無法讓它正常工作;它不會使GUI更具可響應性。GUI在獲取數據時沒有響應
我想申請某種形式的線程上,使得它停止讓我的應用程序不能響應代碼:
public string SQLGet(string query)
{
string post = "q=" + query;
WebRequest request = WebRequest.Create("http://test.com");
request.Timeout = 20000;
request.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(post);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
requestStream = response.GetResponseStream();
StreamReader reader = new StreamReader(requestStream);
string ret = reader.ReadToEnd();
reader.Close();
requestStream.Close();
response.Close();
return ret;
}
編輯:謝謝,LC,我試過很相似的東西。但是我使用這種背景工作的問題在於:我怎麼得到queryResult回到函數調用(在我的情況下SQLGet,並在你的情況)StartQuery?
在我的例子中,返回的字符串將被用作void的字符串被調用的局部變量。
並且可能有很多查詢在同一時間,所以我不想冒險分配給一個全局變量。
請張貼代碼,你啓動一個線程運行`SQLGet`。 – 2009-07-09 03:51:33
目前我沒有使用線程,因爲我不知道如何以他們想要的方式來實現它們。這就是我尋求幫助的原因。 – Phoexo 2009-07-09 07:40:14
更新我的答案以符合您的修改。 – 2009-07-09 15:09:13