Search code examples
c#multithreadingremoting

How to set the apartment state of the thread serving the .Net Remoting call?


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.


Solution

  • 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);
        }