Silverlight 4 COM interop - problem with threads and COM event

Sep 22, 2011 at 10:36 AM

There seems to be an Issue when you read data comming from the serial port. This seems to be caused by the fact that the OnSelectedPortDataReceived event within the SerialPort class is getting called asynchronously, which isn't on the same Silverlight UI thread that it was created on, this causes the out of browser to crash.

The OnSelectedPortDataRecieved method needs to call the DataRecieved event like this.

SynchronizationContext

 

.Current.Post(o => DataReceived(sender, (int) (e.EventType)), null);

  Not like the below example.

DataReceived(sender, (int

)(e.EventType));

 



This solves the Issue, and I was hoping you could please add it to the solution for other developers using this component.

Coordinator
Sep 22, 2011 at 11:30 AM
Edited Sep 22, 2011 at 2:28 PM

Hi jethrob,

thank you for your comment. The problem you ran into was caused by trying to access the UI from within the DataReceived-Callback (e.g. displaying the results in a text-box). That gives you a cross-thread-access exception. Your solution works well for your situation. But as another developer might consider processing the data first instead of just dumping it to the UI, it is better to keep it the way it is.

If you decide to access the UI from a seperate thread -- like the DataReceived-callback -- you can always utilise the dispatcher.

var line = selectedPort.ReadLine(); 
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { textBox.Text += line + "\n"; });

You would put the text in your TextBox like I showed above.

Regards,

Paul

edit: corrected typos ;)

Sep 22, 2011 at 11:46 AM

Hi Paul,

I can't believe I didn't think of that! I guess when I was working on it late last night that solution totally slipped my mind. Thanks a lot for your quick response aswell.

Much appreciated!

Regards,

Jethro

Coordinator
Sep 22, 2011 at 2:29 PM

You are welcome ;).