I developed a proof of concept application that query if WCF support multi-threading.
Now, all what I did is creating a service contract marked with
Try to change the value of the attribute
UseSynchronizationContext=false
Well, by defining your service to be
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode=ConcurrencyMode.Multiple,
UseSynchronizationContext=true)]
you're basically defining your service class to be a singleton (InstanceContextMode.Single
) which certainly isn't the best approach. By defining it as ConcurrencyMode.Multiple
, you make it a multi-threaded singleton - which puts a lot of burden of making sure your code is 200% thread-safe onto your own shoulders.
My recommendation would be to mark your service implementation class as per-call.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall,
ConcurrencyMode=ConcurrencyMode.Single)]
With this approach, the WCF runtime itself will spin up as many service instance classes as needed, to handle your requests. In your example, the WCF runtime will create and start up two instances of ServiceImplementation
, one for each request, and handle the calls concurrently. The big advantage is: since each service instance class only serves one request, you don't need to worry about concurrency management in your code - you're inside a "single-threaded" class and the WCF runtime handles all the issues related to having multiple requests and handling them appropriately.
Update: you're still not showing how your are creating your client-side service proxy, and how you're calling your service. You've posted just about all the server-side code - but not a shred of client-side code.
OK, here's how to do it:
Client1
and Client2
Add Service Reference
to add a service reference to your servicethat will create a bunch of files under that "Service Reference" globe
You now need to instantiate an instance of the client-side proxy in both your client projects:
In Client1:
var instance1 = new ServiceImplementationClient();
In Client2:
var instance2 = new ServiceImplementationClient();
Client1
will call your first method GetDelayedResponse
, while Client2
will call GetDirectResponse
:
In Client1:
instance1.GetDelayedResponse();
In Client2:
instance2.GetDirectResponse();
if you run those two apps simultaneously, you should see that Client2
returns right away, while Client1
will wait for those 8 seconds.
If you have two totally separate clients, and they will get a totally separate service instance on the server, they are totally independant of one another and won't be serializing their calls and won't be blocking each other.