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.
views:
32answers:
2You 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.
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);
}