使用 ServiceThrottlingBehavior 來控制 WCF 服務效能

ServiceThrottlingBehavior 類別會公開可用來限制應用程式層級上所能建立之執行個體或工作階段數目的屬性。 您可以使用這個行為來微調 Windows Communication Foundation (WCF) 應用程式的效能。

控制服務執行個體及同時呼叫的數目

您可以使用 MaxConcurrentCalls 屬性指定透過 ServiceHost 類別主動處理的訊息數目上限,並使用 MaxConcurrentInstances 屬性來指定服務中 InstanceContext 物件的數目上限。

由於決定這些屬性的設定時,一般都是根據相對於負載執行應用程式所獲得的實際經驗,因此我們通常會在應用程式組態檔中使用<serviceThrottling>元素來指定ServiceThrottlingBehavior屬性的設定。

下列程式碼範例簡單示範如何從應用程式組態檔使用 ServiceThrottlingBehavior 類別,將 MaxConcurrentSessionsMaxConcurrentCallsMaxConcurrentInstances 屬性設定為 1。 至於特定應用程式的最佳設定,則需要透過實際經驗來判斷。

<configuration>
  <appSettings>
    <!-- use appSetting to configure base address provided by host -->
    <add key="baseAddress" value="http://localhost:8080/ServiceMetadata" />
  </appSettings>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="Throttled" >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior  name="Throttled">
          <serviceThrottling 
            maxConcurrentCalls="1" 
            maxConcurrentSessions="1" 
            maxConcurrentInstances="1"
          />
          <serviceMetadata 
            httpGetEnabled="true" 
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

確切的執行階段行為將取決於 ConcurrencyModeInstanceContextMode 屬性的值,因為這兩個屬性分別控制可在作業中同時執行的訊息數目,以及 InstanceContext 服務相對於傳入通道工作階段的存留期。

如需詳細資訊,請參閱 MaxConcurrentCallsMaxConcurrentInstances

另請參閱