How to Raise an Event on a Different Thread

  • Thread starter Thread starter Charles Law
  • Start date Start date
C

Charles Law

Suppose a worker thread needs to signal to the main thread that an event has
occurred. Ordinarily, any event raised by the worker thread will be on its
own thread.

How can the worker thread raise an event on the main thread instead?

TIA

Charles
 
Hi Alex

Thanks for the reference. I have been trying with Invoke, and more recently
BeginInvoke, but they both have their problems.

Invoke does not return until the UI thread is free, which causes deadlock
when the UI thread is waiting for the worker thread to do something.

BeginInvoke returns immediately, but the UI is not updated until the thread
is free, which means that updates can occur out of sequence. In particular,
I send data out of the serial port and produce a trace in a window
on-screen. When replies are sent, I add them to the trace. The trace of the
received data is invoked from an event raised by the worker/comms thread.
When there are a lot of exchanges of outgoing and incoming data, the
outgoing data is added to the trace first, and then the incoming data, and
thus the correct sequence is lost.

I was looking for a way for the comms class to raise its 'DataReceived'
event on the UI thread, so that everything would be synchronised. Any ideas?

Charles
 
Hi, Charles

I would stick with BeginInvoke. As I see it you need to check how your trace
is implemented. If you really need to sequence it, you can use some
collection object (Queue, Stack, Hashtable - whatever), to post events in
correct order and then to extract them for display in correct order.
DataReceived event won't solve the problem by itself.

If I get your situation, you can keep the sequence of sent data, but answers
might be not sequenced properly? Possibly you need some contraption to link
your send to your receive. For example, you can save send somewhere or pass
it to receiving thread. Then when you receive answer you can show both using
BeginInvoke. Or you can link the answer to original send and show the link
in your trace. Depends.

It's not very clear for me what is "everything is synchronized". By itself
raising event between the threads is same as raising event on same thread.
Except of course threads synchronization issues. Which are different from
yours.

HTH
Alex
 
Hi Alex

Thanks again.
I would stick with BeginInvoke. As I see it you need to check how your
trace

That was the unhappy conclusion I was coming to. I look forward to the time
when forms and controls are thread-safe ;-)

Charles
 
Back
Top