What's the proper way to clean up a worker thread in .net? I have a thread that looks like this:
private void Thread()
{
while (true)
{
Thread.Sleep(500);
// Do stuff
}
}
In my testing, I commented out all of the // Do Stuff stuff, so it should just be sleeping for half a second, endlessly, without doing anything else. My clean-up method is as follows:
private void KillThread(Thread thread)
{
try
{
if (thread != null)
{
try
{
thread.Interrupt();
if (thread.Join(20000) == false)
thread.Abort();
}
catch
{
thread.Abort();
}
}
}
catch (Exception exception)
{
ProcessLog.WriteError(exception);
}
}
When I run that on the above thread during a FormClosed event, it seems to wait the full 20 seconds, so obviously I'm doing something wrong.
Second, what is the proper way to clean up an HttpListener doing asynchronous listens? I have the following listener callback:
private void ListenerCallback(IAsyncResult result)
{
try
{
HttpListener httpListener = (HttpListener)result.AsyncState;
if (httpListener != null)
{
try
{
HttpListenerContext context = httpListener.EndGetContext(result);
if (context != null)
{
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
if (request != null && response != null)
{
String ipAddress = request.RemoteEndPoint.Address.ToString();
Stream bodyStream = request.InputStream;
Encoding encoding = request.ContentEncoding;
StreamReader reader = new StreamReader(bodyStream, encoding);
ProcessReceived(ipAddress, reader.ReadToEnd());
TextWriter writer = new StreamWriter(response.OutputStream);
writer.Write("OK");
writer.Flush();
response.OutputStream.Close();
}
}
}
catch (Exception exception)
{
ProcessLog.WriteError(exception);
}
httpListener.BeginGetContext(m_HttpListenerCallback, httpListener);
}
}
catch (Exception exception)
{
ProcessLog.WriteError(exception);
}
}
But when I attempt to clean up the object, again on FormClosed, I get "Cannot reference disposed objects" exceptions, I believe from th callback method. My clean-up is simplye:
if (m_HttpListener != null)
m_HttpListener.Close();
I've also tried using Stop(), but both seem to have the same problem. Any help would be much appreciated.
Thank you.
Without order nothing can exist - without chaos nothing can evolve.