daniel lozano
daniel lozano

Reputation: 429

Manipulating threads using VB.NET

This question is about why Microsoft does not allows me to do changes in the interface of my program when I receive something through my serial port.

I am a junior engineer, and in my job, one of the senior programmers has explained to me that when Microsoft open a new thread with information that income from the serial port, it does not allow you to make changes in the interface, and I need to create a new thread using BeginInvoke(...) function to do it.

What I have is an interface, where a Console button is paced into, and when I press the console button, a RichtextBox is opened. My program can receive from serial port text that needs to be printed in that RichtextBox, but nothing appeared.

My question is, why Microsoft does not allow me to print in the richtextbox when I receive something through serial port when using a thread created by itself? I do not understand why I need to create a new thread to do it. Microsoft gives a specific reason for this?

I hope you can understand me, it is a little bit difficult to explain it hehe.

Thanks!!

Upvotes: 0

Views: 43

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54487

It's not that you need to create a new thread at all. All the necessary threads already exist.

What's actually happening is that all your UI elements are owned by the UI thread while the SerialPort raises its DataReceived event on a secondary thread. That makes perfect sense because you wouldn't want receiving data from the COM port to make your UI freeze. Because changes to the UI can only be made on the UI thread, you can't do so directly from the DataReceived event handler. You must marshal a method call to the UI thread in order to do so. That is quite simple once you know how.

You're not creating any new threads. You're receiving data on one existent thread and then using on another existent thread.

Upvotes: 1

Related Questions