10

I have a WCF service which includes UI components, which forces me to be in STA mode.

How do I set the service behaviour to STA-mode?


The service uses a reference to a WPF DLL file which opens a UI window (used as view port) for picture analysis. When the service is trying to create an instance of that item (inherits from window) it throws an exception:

The calling thread must be an STA

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

1

I'm doing something similar to you.

My solution was to route all calls through an STA thread queue. I used a threadsafe collection from the new parallel framework to queue up Actions I wanted to run on a STA thread. I then had X number of STA threads that continually checked the queue for new actions to execute.

  • 2
    And, now, I'm just using a custom [SynchronizationContext](http://msdn.microsoft.com/en-us/magazine/cc163321.aspx#S4) for this now. Much better solution. –  Aug 22 '11 at 16:51
0

ServiceBehaviour attribute allows you to specify behavior. In your case for single thread you would use following:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
public class Service : IService
{
}

You might want to read about different InstanceContextModes to help you better choose on how you want service to behave.

You also need to add to your app.config new service behavior (or edit existing one):

    <behavior name="wsSingleThreadServiceBehavior">
      <serviceThrottling maxConcurrentCalls="1"/>
    </behavior>

and in your behavior configuration in same app.config set behaviorConfiguration like following:

 <service behaviorConfiguration="wsSingleThreadServiceBehavior" name="IService">
    <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsEndpointBinding" name="ConveyancingEndpoint" contract="IService" />
  </service>

Hope this saves you some time

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
0

I would investigate using the [STAThread] attribute to switch the threading model. e.g.

[STAThread]
static void Main()
{
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new Host() };
        ServiceBase.Run(ServicesToRun);
}

Description of the STAThread attribute

But I'm confused why you're using UI components in a web service at all. Can you explain a bit more about why you're trying to do this?

John Sibly
  • 22,782
  • 7
  • 63
  • 80
  • 1
    I know the comment comes a bit late, but nonetheless - don't use this approach! Basically, this will cause deadlock with Finalizer thread so finalization will not be working causing resources leaks. I'll add url with more details soon. – Mihailo Apr 07 '11 at 14:31
  • http://stackoverflow.com/questions/2001667/net-windows-service-needs-to-use-stathread – GregC Apr 28 '11 at 05:54