Link to home
Start Free TrialLog in
Avatar of gregasm
gregasm

asked on

Raising events to UI from a multithreaded object... need critical section?

Hi,

Just want to verify my understanding of events and threading with you guys. So tell me if I am wrong... and please let me know why.

I have a multithreaded object raising event from multiple concurrent threads. The events are being handled by the UI in a single event handler.

Even though multiple events may be raised concurrently, they are all marshalled onto the UI thread one at a time (queued ) and therefore the UI thread need not use a critical section to protect the UI variables in the event handler.

True or false and why?
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

I would have to agree with you.

Just make sure that you are using Delegates to properly update the UI and not attempting to update the UI directly in the event handler.
Avatar of gregasm
gregasm

ASKER

Idle_Mind, I thought the event handler is run on the UI thread?

I thought that only if the UI is modified directly from the non-ui thread then delegates were needed... again, to marshal the call onto the UI thread.

If the UI thread is handling the event, then is there still the need to use a delegate to "invoke" the actual UI-modifying code?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
On a side note...

In VB.Net 2003 this appears to work (but as I said is incorrect and Delegates should be used):

    Private Sub te_WhoAmI(ByVal name As String)
        Label1.Text = name      ' <----- WRONG...this may work but it won't always!
    End Sub

If you place this same code in VB.Net 2005 you get an exception:

    "Cross-thread operation not valid: Control 'Label1' accessed from a thread other than the thread it was created on."
  Source="System.Windows.Forms"

So the .Net framework has gotten smarter and it points you here for how to solve the problem:
http://msdn2.microsoft.com/en-us/library/ms171728.aspx