views:

53

answers:

2

Hi:

This is a strange problem I encountered. I have an window application written in c# to do testing. It has a MDI parent form that is hosting a few children forms. One of the forms launch test scripts by creating processes and capture the scripts output to a text box. Another form open serial port and monitoring the status of the device I am working on(like a shell). If I ran both of them together, the output of the script seems only appear in the text box after the test is done. However, If I don't open the serial port form, the output of the script is captured in real time.

Does anyone knows what's causing the problem? I notice the onDataReceived evenT handler for serial port form has a [STAThread] header to it. Will this cause the serial port thread having higher priority than other processes?

Thanks in advance.

A: 

I don't know of any case where the [STAThread] attribute will cause the thread to have higher priority.

From this SO question that discusses the differences between STA and MTA threads:

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of it's runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Zach Johnson
+1  A: 

STATHREAD is required for a UI thread. From MSDN:

Indicates that the COM threading model for an application is single-threaded apartment (STA).

Also, a windows form application will only have a single UI thread. It sounds like what you may need to do to have a responsive UI is use a background worker thread to control running your script, and have it communicate changes back to the UI thread.

Justin Ethier
+1 It does sound like the problem is the UI thread being blocked.
Zach Johnson
I used delegate function approach to update UI in my window form. It worked find until I ran them with the serial port form. Is there a way to see what's going on using debugger provided by visual studio?I want to see why the UI thread is blocked if serial port form is opened.
alex