如何设置服务 .Net Remoting 调用的线程的单元状态?

发布于 2024-09-26 05:12:29 字数 157 浏览 3 评论 0原文

我的程序的客户端和服务器都标记为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花开浅夏 2024-10-03 05:12:29

远程处理无法做到这一点,STA 线程的硬性要求是它还泵送消息循环。您确实必须创建自己的线程,在启动之前使用 Thread.SetApartmentState() 将其切换到 STA。并使用 Application.Run() 和虚拟表单来启动消息循环。然后,您可以使用 Control.BeginInvoke() 将远程处理线程的调用编组到这个新线程。

请注意,由于您已经为服务器启动了一个 STA 线程,因此该线程可以很好地完成这项工作。将其粘贴到您的表单类中以防止其可见:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            this.CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }

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:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            this.CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }
只是一片海 2024-10-03 05:12:29

您可以创建另一个线程并将其标记为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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文