次のコードが少しあります:
フォーム上:
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);
}
}
}
停止ボタンをクリックしようとすると問題が発生します。フォームがブロックされています。私の停止機能が正しいか間違っているかはわかりません。アドバイスをいただけますか?ありがとう