I want to create a background thread that's owned by an object. When that object is no longer needed, so is its background thread.
pseudo code of what I currently have:
ResetEvent _isCanceled
ResetEvent _hasWork
ThreadSafeQueue _workItems
Init()
new BackgroundThread(ThreadLoop).Start()
AddWork(work)
_workItems.Enqueue(work)
_hasWork.Set()
Dispose()
_isCanceled.Set()
ThreadLoop()
while(!_isCanceled)
if(_hasWork)
Execute(_workItems.Dequeue())
if(_workItems.IsEmpty)
_hasWork.Reset()
WaitHandle.WaitAny(_isCanceled, _hasWork)
The problem is that if someone (not me of course) forgets to call Dispose(), the thread will never be stopped. What I understood about Finalize is that you can't refer to any members, because you must assume they are null-ed already.
So how can I stop the background thread if the owning object is or gets gc-ed?