I have a class that implements IDisposable. The class contains a thread and the thread is closed in the Dispose method using Thread.Join(...)
My issue however is that if I run my class like this:
static void Main(string[] args)
{
var class = new MyClass();
class.Run();
}
when the application closes, it forcefully closes the thread without waiting for it to finish execution.
However, if I run it like this:
static void Main(string[] args)
{
using (var class = new MyClass())
{
class.Run();
}
}
the thread finishes what it started and ends gracefully. What is the using statement doing that's allowing the thread to finish executing?
My hunch is that with the first method, because the application has exited, it forcefully closes the thread without waiting for it to finish. However, under the using block, the application is still running so it has time to close the thread then exit the application.
If my hunch is correct can you let me know why the application doesn't wait on the thread the be finished before closing?
Edit:
~ElasticBase()
{
Dispose(false);
}
public virtual void Initialize()
{
workerThread = new Thread(ProcessData)
{
Name = "ElasticBase thread",
IsBackground = true
};
IsInitialized = true;
}
public virtual void Shutdown()
{
if (workerThread.IsAlive)
{
IsInitialized = false;
lock (syncObject)
{
if (!workerThread.Join(10000))
{
workerThread.Abort();
}
workerThread = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool calledFromDispose)
{
Shutdown();
}
As you can see with the code above. The Shutdown method is called in Dispose. If I DON'T call Dispose explicitly and I DON'T use a using block, the Thread.Join method closes without finishing. However, if I do call Dispose explicity or use a using block, suddenly Thread.Join works as expected. Why?
TLDR;
When Dispose is invoked through the finalizer, Thread.Join doesn't wait to finish. When dispose is explicitly invoked (through manually calling it or with a using statement), Thread.Join waits to finish.