如何设置服务 .Net Remoting 调用的线程的单元状态?
我的程序的客户端和服务器都标记为 STAThread,并且我在调试器中验证了我进行调用的线程被标记为 STA。在服务器端,我验证了设置服务器时程序本身被标记为STA。然而,实际的 .Net 远程调用是通过标记为 MTA 的线程完成的。当我的服务方法访问需要 STA 线程的资源时,是否可以更改此行为。
The client and server of my program are both marked STAThread, and I verified in the debugger that the thread I make the call from is marked as STA. On the server side, I verified that the program itself when setting up the server is marked STA. However the actual .Net remoting call is done via a thread which is marked MTA. Is there anyway to change this behavior as my service method accesses resources which require an STA thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
远程处理无法做到这一点,STA 线程的硬性要求是它还泵送消息循环。您确实必须创建自己的线程,在启动之前使用 Thread.SetApartmentState() 将其切换到 STA。并使用 Application.Run() 和虚拟表单来启动消息循环。然后,您可以使用 Control.BeginInvoke() 将远程处理线程的调用编组到这个新线程。
请注意,由于您已经为服务器启动了一个 STA 线程,因此该线程可以很好地完成这项工作。将其粘贴到您的表单类中以防止其可见:
Remoting cannot do this, a hard requirement for an STA thread is that it also pumps a message loop. You'll indeed have to create your own thread, use Thread.SetApartmentState() to switch it to STA before you start it. And use Application.Run() with a dummy form to start the message loop. You can then use Control.BeginInvoke() to marshal the call from the remoting thread to this new thread.
Note that since you already started an STA thread for the server, that thread would do the job just fine. Paste this into your form class to prevent it from getting visible:
您可以创建另一个线程并将其标记为STA来读取资源。我假设它不会用于访问 COM 对象等。在这种情况下,应该没问题,但是创建这个额外线程会产生开销。
You can create another thread and mark it as STA to read the resources. I assume it is not going to be used to access COM objects and so on. In that case, it should be ok, but there is an overhead of creating this additional thread.