问题描述
您好,
我有一个基于C#Window Services的应用程序,其中使用需要在单线程单元[STA]上运行的ActiveX。那个ActiveX做TCP通信。
如果我将它作为MTA运行,那么它会给出异常ActiveX控件无法实例化,因为当前线程不在单线程单元中。
现在我找到了两种在STA中运行它的方法。
1)在入门级应用方法中写入[STAThread]。如下所示:
Hello,
I have one C# Window Services based application in which using ActiveX which required to be run on Single thread apartment [STA]. That ActiveX doing TCP communication.
If I run it as MTA then it gives exception "ActiveX control cannot be instantiated because the current thread is not in a single-threaded apartment."
Now I found two ways to run it in STA.
1) Write [STAThread] in entry level method of application. Like below:
[STAThread]
static void Main()
2)启动新线程并将公寓状态设置为STA如下所示
2) Start New thread and set apartment state to STA like below
Thread t = new Thread(() => StartTCPCommunication());
t.SetApartmentState(ApartmentState.STA);
t.Start();
现在我的问题是上述两种方式之间有什么区别。
因为我的应用程序结构就像我不能使用Way#1因为我的应用程序作为Windows服务运行。所以,即使我使用方式#1,它也会给我上面提到的ActiveX异常。
如果我将Windows服务转换为Windows桌面应用程序,那么相同的代码可以正常工作#1
但我需要Windows服务,所以我需要使用Way#2,但是当我使用它时,我无法进行TCP通信,甚至没有任何例外。
那么任何人都可以帮我解决问题吗?或其他方式?
提前谢谢
Now my question is what is the difference between above 2 ways.
Because my application structure is like that I can't use Way#1 becuase my appication running as Windows Service. so even if I use way#1 it give me ActiveX exception mentioned above.
If I convert windows services to Windows Desktop application then same code working fine with Way#1
But I need windows service so I need to use Way#2, but when I used that I can not do TCP communication and even not get any exception.
So can any one help me to figure out the issue ? or some alternate way ?
Thanks in advance
推荐答案
这篇关于哪些是在单线程单元[STA]中运行C#应用程序的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!