Thread: Need to synchronize worker thread exit with main thread, but worker thread uses Invok

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396

    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?
    Last edited by brewbuck; 11-19-2011 at 07:34 PM.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. URLDownloadToFile dont work in worker thread
    By hanhao in forum Windows Programming
    Replies: 2
    Last Post: 07-02-2007, 12:49 AM
  2. Replies: 2
    Last Post: 07-01-2007, 07:11 AM
  3. Message box as thread to stop main thread
    By Yasir_Malik in forum Windows Programming
    Replies: 8
    Last Post: 04-11-2006, 11:07 AM
  4. pointer to main thread from worker thread?
    By draegon in forum C++ Programming
    Replies: 2
    Last Post: 10-27-2005, 06:35 AM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM