Search code examples
.netwcfthread-safety

ConcurrencyMode.Multiple in stateless WCF services


We currently have multiple WCF services which are using the default ServiceBehavior. Due to issues with scalability, we are looking at applying the ConcurrencyMode = ConcurrencyMode.Multiple attribute to improve throughput. All of our service calls are completely stateless, for example:

PersonService.cs:

public class PersonService : IPersonService
{
  public GetPersonResponse GetPerson(GetPersonRequest request)
  {
    GetPersonResponse response = new GetPersonResponse();

    try
    {
      response.Person = Person.GetPerson(request.PersonID);

      return response;
    }
    catch (Exception ex)
    {
      return (GetPersonResponse) response.SetException(ex);
    }
  }
}

Person.cs:

public static class Person
{
  public static PersonDataContract GetPerson(int personID)
  {
    PersonDataContract pdc = null;

    // load contract from db...
    pdc = Database.Load<PersonDataContract>(personID);

    // Address is another static class in the same pattern as Person
    pdc.Addresses = Address.GetAddressesForPerson(personID);

    return pdc;
  }
}

All methods in the Person class are static to help performance, and stateless for thread safety. The Database class is also static, but its methods reference static variables.

In this context, what needs to be made thread-safe in order for ConcurrencyMode.Multiple to not cause multithreading issues? I'm thinking only the Database class, but does the Person class (and all other classes that follow the same pattern) need to be locked as well?

I know that all classes should be bulletproofed for maximum safety, but unfortunately time constraints don't allow this... we need to get code delivered ASAP.


Solution

  • If you use the default "per call" activation mechanism (which works great if your services are completely stateless), there's absolutely no point in adding the ConcurrencyMode.Multiple since each incoming request will get its own instance of the service class to handle its request. This is the preferred and recommended setting for InstanceContextMode.

    Read more about instance management in WCF at MSDN Magazine: Discover Mighty Instance Management Techniques For Developing WCF Apps

    The only time when you benefit from using ConcurrencyMode.Multiple is when you have a singleton WCF service - but this is highly discouraged, since it's a) a big hindrance for scalability, and b) extremely tricky to program properly.

    My recommendation would be: try to narrow down more in detail what really causes the performance problems. Just jumping into ConcurrencyMode.Multiple seems like the wrong approach - it's very messy, very labor-intensive, lots of code, lots of chance of getting it wrong......