Which code segment should you use to set the service behavior?

You are developing a Windows Communication Foundation (WCF) service.
One of the service operations contains the following code.

private static int counter = 0;
[OperationContract]
public void IncrementCount()
{
counter++;
}

You need to set a service behavior that prevents two or more threads from incrementing the counter variable at the same time.
Which code segment should you use to set the service behavior?

You are developing a Windows Communication Foundation (WCF) service.
One of the service operations contains the following code.

private static int counter = 0;
[OperationContract]
public void IncrementCount()
{
counter++;
}

You need to set a service behavior that prevents two or more threads from incrementing the counter variable at the same time.
Which code segment should you use to set the service behavior?

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

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

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

D.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]

Explanation:
“prevents two or more threads…at the same time” –> ConcurrencyMode.Single

ConcurrencyMode Enumeration
(http://msdn.microsoft.com/en-us/library/system.servicemodel.concurrencymode.aspx)

InstanceContextMode Enumeration
(http://msdn.microsoft.com/en-us/library/system.servicemodel.instancecontextmode.aspx)



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Igor

Igor

I guess the correct answer is “A”. In case of “B” 2 or more clients can access static int counter simultaneously even if ConcurrencyMode.Single.

mark

mark

I agree on the answer of ‘A’.
B is unsafe.