WCF ConcurrencyMode Single and InstanceContextMode PerCall
Asked Answered
N

2

22

I have an issue with my wcf service config. I would like every call to my service create a new instance of the service. For the concurrency I would like to one call is finished before another start.

Thus if I have a service like this one:

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single,
InstanceContextMode=InstanceContextMode.PerCall)]
public class MyService: IMyService
{
    public bool MyServiceOp()
    {
        Debug.WriteLine("thread "+ 
            Thread.CurrentThread.ManagedThreadId.ToString());
        Debug.WriteLine("start operation ");
        Do_work()
        Debug.WriteLine("end operation");
        return true;
    }
}

When I call it with multiple call in a loop, the trace give:

thread 1
thread 2
start operation
start operation
end operation
end operation

While I would like to have this:

thread 1 start operation end operation
thread 2 start operation end operation

Is this possible? Thank you

Neve answered 19/8, 2011 at 13:53 Comment(2)
The only way to synchronize threads as you describe across separate service calls is to configure the service with both concurrency and instance context set to single (i.e. the singleton pattern). If you do this your application will have virtually no scalability since you are creating a wonderfully efficient bottleneck ;)Indication
@Sixto: Concurrency and context lifetime are two different things. A Singleton is not required.Unremitting
U
21

I know this question was marked as answered, but there is a better alternative:

If you use a InstanceContextMode.Single then you will reuse the same instance for all calls. If your service is long running this requires your code to manage resources perfectly, since it will never be garbage collected without a service restart.

Instead keep the InstanceContextMode.PerCall for “every call to my service creates a new instance” and then use throttling: Set the max concurrent instances to 1. The MSDN documentation does exactly this as one of the examples.

Unremitting answered 22/8, 2011 at 15:19 Comment(0)
S
5

What you have there will result in a new instance of the service spinning up with each request (that's what PerCall does).

This should do it:

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single, InstanceContextMode=InstanceContextMode.Single)]

FYI if you do this you'll lose all scalability. You'll have a single instance of a single threaded service to respond to all requests.

Sorcerer answered 19/8, 2011 at 14:13 Comment(1)
Does this address this requirement specified in the OP?: "I would like every call to my service create a new instance of the service"Attaint

© 2022 - 2024 — McMap. All rights reserved.