开发者

STAThread and Process output capture in c#

开发者 https://www.devze.com 2022-12-23 17:37 出处:网络
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 f开发者_高级运维orms. One of the forms launch

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 f开发者_高级运维orms. 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.


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.


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.

0

精彩评论

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

关注公众号