开发者

C# Events firing on wrong thread

All

I have an application that allows a user to communicate with multiple serial devices. A manager class is used to start the application, which creates a new thread for each serial device. Inside this thread, the serial device is created and the thread and serial device object are stored inside the manager class for later when needed.

The serial device class then creates a com port class on it's own new thread which is used to connect to the com port and send / receive data. When data is received an event is fired up to the serial device class which in turn fires an event to the manager class, which in turn fires an event to the UI to alert the user that new data has arrived.

My problem comes that when the com port class fires it's event to notify the serial port class, the serial port class receives the event and continues processing under the com port thread. Likewise if the user sends any information down to the com port, it all runs under the UI thread.

I will add code as an edit later, but for now, if anyone can spot anything obvious I would be seriously greatful.

I have tried receiving the event in the serial device class and then invoking a method to see if that makes it run under the correct thread but that was no good.

I know the serial device thread is running as I do an Application.Run inside the class after it's created it's com port classes.

I'm not using any background workers as these threads are meant to exist for the life of the application and I understand background workers are meant to be used for short running calculations.

Many thanks

EDIT:

Forgot 开发者_Python百科to mention, this is a Winforms app in .NET 2.0, so no Dispatcher available

EDIT: Okay, so it looks like that the information is being passed up inside the DataReceived thread (I think as it isn't the com port thread either). I also tried using a BackgroundWorker for the serial device class but this also didn't make any difference. Help?


.NET 2.0 has SynchronizationContext. It's a slight pain (you have to pass the context from the UI thread to the others) but it should do the trick.

More info here: http://msdn.microsoft.com/en-us/magazine/gg598924.aspx


It sounds as if you need to create a kind of messaging mechanism to send messages from the UI thread to the correct port-thread. A queue might work. Let the UI thread post messages on the queue and have the port-thread process these messages.

Switching from the port-thread to the UI thread can be done using Dispatcher.CurrentDispatcher

Is this what you are looking for?

EDIT I am assuming a WinForms application

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜