A Thread Syncing Shared-Subroutine Strategy

NeuralJack

Centurion
Joined
Jul 28, 2005
Messages
138
I have a subroutine that is accessed by multiple threads. The subroutine(let's call it DisplayMessge()) invokes the GUI thread to create a form, if it's not already open. The form that is open basically just displays messages that can come from any of those threads.

So, to ensure that only one form is opened, I put in an AutoResetEvent that envelopes the 'If form doesnt exist create it' part. Now, in order for other non-gui threads to create the new form, if required, they have to invoke the GUI thread. But, if the gui thread is executing code, the invoke will not execute until it's done. Well, if the GUI thread happens to use the Subroutine DisplayMessage() while another thread is waiting to Invoke the GUI thread to create the form, then the GUI thread will also wait ont he AutoresetEvent and you've got a nice application hang.

When the GUI thread blocks on the autoresetevent it will still not allow other threads to invoke the GUI thread, and unclog everything. So, I was thinking a strategy here would be to find out what the GUI threadID is, and if the current thread that is executing the DisplayMessage() IS the GUI thread, then skip the AutoResetEvent.

So, main question- Is there a good way to get the GUI ThreadID from another thread?

Other question - Something I can do is grab the GUI ThreadID upon application startup. Then I can compare that number to the current threadID in DisplayMessage() to determine if i should use the AutoResetEvent or not(do not use the autoresetevent if it's the GUI thread). I'm assuming the GUI ThreadID number will never change. Do you think that'd be an ok strategy? Got any others to suggest?
 
I just thought of a better solution. I dont need to compare thread IDs. I can simply do :

If mainform.InvokeRequired Then
'skip the AutoResetEvent to create the form
Else
'do the autoresetevent to create the new form
endif

I'll probably go with that. I hate to come up with a decent solution after I just post. Mainform.InvokeRequired Should let me know if the current thread is the GUI thread or not.
 
Last edited:
Back
Top