I have an component that is processing multiple web requests each in separate thread. Each WebRequest processing is synchronous.
public class WebRequestProcessor:System.ComponentModel.Component
{
List<Worker> tlist = new List<Worker>();
public void Start()
{
foreach(string url in urlList){
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start(url);
tlist.Add(workerThread);
}
}
}
public class Worker
{
// This method will be called when the thread is started.
public void DoWork(string url)
{
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url);
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
// process stream
}
}
Now I have to find optimal way how to cancel all requests.
One way is to convert each synchronous WebRequest into async and use WebRequest.Abort to cancel processing.
Another way is to release thread pointers and allow all threads to die using GC.