我有一些一些代碼如下:使用Abort()停止多線程時凍結GUI?
在表:
List<WebRequestUri> lwebrequest = new List<WebRequestUri>();
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ParameterizedThreadStart((object context) =>
{
DoWork();
}));
thread.IsBackground = true;
thread.Start();
}
void DoWork()
{
lwebrequest = new List<WebRequestUri>();
for (int i = 0; i < 100; i++)
{
WebRequestUri wp = new WebRequestUri();
wp.Start();
lwebrequest.Add(wp);
}
}
private void Stop_Click(object sender, EventArgs e)
{
for (int i = 0; i < lwebrequest.Count; i++)
{
lwebrequest[i].Abort();
}
}
工人階級:
class WebRequestUri
{
Thread thread = null;
WebRequest webRequest = null;
WebResponse webResponse = null;
StreamReader sr = null;
public void Start()
{
thread = new Thread(new ParameterizedThreadStart((object context) =>
{
SendRequest();
}));
thread.IsBackground = true;
thread.Start();
}
public void Abort()
{
if (webResponse != null) webResponse.Close();
if (webRequest != null) webRequest.Abort();
if (thread != null) thread.Abort();
}
public void SendRequest()
{
webRequest = WebRequest.Create("http://google.com");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "GET";
try
{
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
catch (WebException)
{
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
sr = new StreamReader(webResponse.GetResponseStream());
string response = sr.ReadToEnd();
Console.Write(response);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
我得到的一個問題,當我嘗試單擊停止按鈕。我看到我的表單被阻止。我不確定我的停止功能是對還是錯。你能給我一些建議嗎?謝謝
如果我使用bool變量並將其設置爲「true」時,我想停止線程,我認爲它會非常緩慢。因爲請求需要在bool變量=「true」之後執行。所以它不會立即停止。對於我的問題,Vitaliy有你的想法嗎?謝謝。 – 2012-08-20 01:34:28
@HùngLêXuân,的確,它不會馬上停止。但是你可以在一定程度上控制抽樣的粒度。請參閱我的編輯。 – Vitaliy 2012-08-20 05:00:48