並行範例示範如何使用ServiceBehaviorAttribute與ConcurrencyMode列舉一起,控制服務實例是循序還是並行處理訊息。 此範例是以實作服務合約的 ICalculator
為基礎。 此範例定義了一個新合約 ICalculatorConcurrency
,該合約繼承自 ICalculator
,並提供兩項額外功能來檢查服務並行處理的狀態。 藉由變更並行設定,您可以執行客戶端來觀察行為變更。
在此範例中,用戶端是控制台應用程式(.exe),而服務是由 Internet Information Services (IIS) 所裝載。
備註
此範例的安裝程式和建置指示位於本主題結尾。
有三種可用的並行模式:
Single
:每個服務實例一次處理一則訊息。 這是預設並行模式。Multiple
:每個服務實例會同時處理多個訊息。 服務實作必須是線程安全,才能使用此併發模式。Reentrant
:每個服務實例一次處理一則訊息,但可以接受再進入的呼叫。 服務只會在呼叫時接受這些呼叫。 Reentrant 會在 ConcurrencyMode.Reentrant 範例中示範。
並行存取的使用與實例模式相關。 在 PerCall 實例化中,併發性並不相關,因為每個訊息都會由新的服務實例處理。 在Single實例化中,Single或Multiple的並行性是相關的,這取決於單一實例是否循序或同時處理訊息。 在實例化PerSession時,任何並行模式都有可能是相關的。
服務類別會透過[ServiceBehavior(ConcurrencyMode=<setting>)]
屬性來指定並行行為,如下列程式代碼範例所示。 藉由變更註解掉的行,您可以實驗 Single
和 Multiple
的並行模式。 請記得在變更並行模式之後重建服務。
// Single allows a single message to be processed sequentially by each service instance.
//[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
// Multiple allows concurrent processing of multiple messages by a service instance.
// The service implementation should be thread-safe. This can be used to increase throughput.
[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
// Uses Thread.Sleep to vary the execution time of each operation.
public class CalculatorService : ICalculatorConcurrency
{
int operationCount;
public double Add(double n1, double n2)
{
operationCount++;
System.Threading.Thread.Sleep(180);
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
operationCount++;
System.Threading.Thread.Sleep(100);
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
operationCount++;
System.Threading.Thread.Sleep(150);
return n1 * n2;
}
public double Divide(double n1, double n2)
{
operationCount++;
System.Threading.Thread.Sleep(120);
return n1 / n2;
}
public string GetConcurrencyMode()
{
// Return the ConcurrencyMode of the service.
ServiceHost host = (ServiceHost)OperationContext.Current.Host;
ServiceBehaviorAttribute behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
return behavior.ConcurrencyMode.ToString();
}
public int GetOperationCount()
{
// Return the number of operations.
return operationCount;
}
}
此範例預設會使用 Multiple 並行與 Single 實例化。 用戶端程式代碼已修改為使用非同步代理。 這可讓客戶端對服務進行多個呼叫,而不需要等候每個呼叫之間的回應。 您可以觀察服務並行模式的行為差異。
當您執行範例時,作業要求和回應會顯示在用戶端控制台視窗中。 服務的並行模式隨即顯示,系統會呼叫每個作業,然後顯示作業計數。 請注意,當併行模式為 Multiple
時,結果會以與呼叫方式不同的順序傳回,因為服務會同時處理多個訊息。 藉由將並行模式變更為 Single
,結果會依呼叫的順序傳回,因為服務會循序處理每個訊息。 在客戶端視窗中按 ENTER 鍵以關閉用戶端。