Need to synchronize worker thread exit with main thread, but worker thread uses Invok
I have a problem for which I have a solution, but the solution feels like a hack. I am not a seasoned .NET programmer, let's just get that out there right away.
I have a worker thread which accesses (reads) a container. The container is also accessed (updated) by the UI thread. Instead of locking the container, I actually shut the worker thread down completely, change the container, then spin up the worker thread again. The worker thread only does read accesses to the container, so this ensures mutual exclusion during updates.
To synchronize with the termination of the worker thread, I wait on an AutoResetEvent in the main thread.
Problem: The worker thread does some updates to a DataSet which is bound to some UI controls. The updates cause events to fire which are connected to the UI controls. Thus the updates need to be performed on the UI thread -- I use Invoke to do this. The problem is, this can deadlock during shutdown of the worker thread because it might be in the middle of an Invoke on the UI thread, while the UI thread goes to sleep waiting on the AutoResetEvent. Oops.
My current workaround is for the UI thread to call WaitOne() with a timeout of zero, and while the event is not set, I call Application.DoEvents() to pump the main thread's event loop.
This works, but I have a feeling it sucks and I'm missing something. Any suggestions?