我有一些代码如下:
在表格上:
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);
}
}
}
当我尝试单击停止按钮时,我遇到了一个问题。我看到我的表格被阻止了。我不确定我的停止功能是对还是错。你能给我一些建议吗?谢谢