工作階段、執行個體與並行Sessions, Instancing, and Concurrency

工作階段 」(Session) 是兩個端點之間所傳送之所有訊息的相互關聯。A session is a correlation of all messages sent between two endpoints. 執行個體 」(Instancing) 是指控制使用者定義之服務物件的存留時間,以及其相關的 InstanceContext 物件。Instancing refers to controlling the lifetime of user-defined service objects and their related InstanceContext objects. 並行 」(Concurrency) 是指控制在 InstanceContext 中同時執行的執行緒數目。Concurrency is the term given to the control of the number of threads executing in an InstanceContext at the same time.

本主題將說明這些設定、這些設定的使用方式,以及這些設定間的各種互動。This topic describes these settings, how to use them, and the various interactions between them.

工作階段Sessions

當服務合約將 ServiceContractAttribute.SessionMode 屬性設定為 SessionMode.Required時,該合約會指出所有的呼叫 (即支援呼叫的基礎訊息交換模式) 必須是同一個對話的一部分。When a service contract sets the ServiceContractAttribute.SessionMode property to SessionMode.Required, that contract is saying that all calls (that is, the underlying message exchanges that support the calls) must be part of the same conversation. 如果合約指定其允許工作階段,但不需要工作階段,則用戶端可以連線,並選擇是否要建立工作階段。If a contract specifies that it allows sessions but does not require one, clients can connect and either establish a session or not. 如果工作階段終止並透過相同之工作階段型的通道傳送訊息,就會擲回例外狀況。If the session ends and a message is sent over the same session-based channel an exception is thrown.

WCF 會話具有下列主要的概念功能:WCF sessions have the following main conceptual features:

  • 工作階段是由呼叫的應用程式明確地初始化及終止。They are explicitly initiated and terminated by the calling application.

  • 工作階段期間傳遞的訊息是依其接收的順序進行處理。Messages delivered during a session are processed in the order in which they are received.

  • 工作階段會將一群訊息互相關聯為對話。Sessions correlate a group of messages into a conversation. 此相互關聯的意義是一種抽象概念。The meaning of that correlation is an abstraction. 例如,某個工作階段架構通道可能會根據共用的網路連線將訊息相互關聯,而另一個工作階段架構通道可能會根據訊息本文內的共用標記將訊息相互關聯。For instance, one session-based channel may correlate messages based on a shared network connection while another session-based channel may correlate messages based on a shared tag in the message body. 這些可以衍生自工作階段的功能視相互關聯的本質而定。The features that can be derived from the session depend on the nature of the correlation.

  • 沒有與 WCF 會話相關聯的一般資料存放區。There is no general data store associated with a WCF session.

如果您熟悉 System.Web.SessionState.HttpSessionState ASP.NET 應用程式中的類別及其所提供的功能,您可能會注意到這種會話與 WCF 會話之間的下列差異:If you are familiar with the System.Web.SessionState.HttpSessionState class in ASP.NET applications and the functionality it provides, you might notice the following differences between that kind of session and WCF sessions:

  • ASP.NET 會話一律是由伺服器起始。ASP.NET sessions are always server-initiated.

  • ASP.NET 會話會隱含地排序。ASP.NET sessions are implicitly unordered.

  • ASP.NET 會話提供跨要求的一般資料儲存機制。ASP.NET sessions provide a general data storage mechanism across requests.

用戶端應用程式和服務應用程式會以不同的方式與工作階段互動。Client applications and service applications interact with sessions in different ways. 用戶端應用程式會初始化工作階段,接著並接收及處理在工作階段內傳送的訊息。Client applications initiate sessions and then receive and process the messages sent within the session. 服務應用程式可以將工作階段當做擴充點使用,以便加入其他行為。Service applications can use sessions as an extensibility point to add additional behavior. 其做法是直接使用 InstanceContext 或實作自訂的執行個體內容提供者。This is done by working directly with the InstanceContext or implementing a custom instance context provider.

實例Instancing

執行個體行為 (使用 ServiceBehaviorAttribute.InstanceContextMode 屬性設定) 會控制 InstanceContext 對傳入訊息建立回應的方法。The instancing behavior (set by using the ServiceBehaviorAttribute.InstanceContextMode property) controls how the InstanceContext is created in response to incoming messages. 根據預設,每一個 InstanceContext 都會與一個使用者定義的服務物件產生關聯,因此 (在預設的情形下) 設定 InstanceContextMode 屬性也會控制使用者定義之服務物件執行個體。By default, each InstanceContext is associated with one user-defined service object, so (in the default case) setting the InstanceContextMode property also controls the instancing of user-defined service objects. InstanceContextMode 列舉型別 (Enumeration) 會定義執行個體模式。The InstanceContextMode enumeration defines the instancing modes.

以下為可用的執行個體模式:The following instancing modes are available:

  • PerCall:為每個用戶端要求所建立的新 InstanceContext (因此為服務物件)。PerCall: A new InstanceContext (and therefore service object) is created for each client request.

  • PerSession:為每個新用戶端工作階段所建立的新 InstanceContext (因此為服務物件),並維持該工作階段的存留期 (這麼做需要支援工作階段的繫結)。PerSession: A new InstanceContext (and therefore service object) is created for each new client session and maintained for the lifetime of that session (this requires a binding that supports sessions).

  • Single:單一的 InstanceContext (因此為服務物件),負責處理所有應用程式之存留期的用戶端要求。Single: A single InstanceContext (and therefore service object) handles all client requests for the lifetime of the application.

下列程式碼範例示範預設的 InstanceContextMode 值,在服務類別上會明確地設定 PerSessionThe following code example shows the default InstanceContextMode value, PerSession being explicitly set on a service class.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class CalculatorService : ICalculatorInstance
{
    ...  
}  

ServiceBehaviorAttribute.InstanceContextMode 屬性控制釋放 InstanceContext 的頻率時, OperationBehaviorAttribute.ReleaseInstanceModeServiceBehaviorAttribute.ReleaseServiceInstanceOnTransactionComplete 屬性會控制釋放服務物件的時機。And while the ServiceBehaviorAttribute.InstanceContextMode property controls how often the InstanceContext is released, the OperationBehaviorAttribute.ReleaseInstanceMode and ServiceBehaviorAttribute.ReleaseServiceInstanceOnTransactionComplete properties control when the service object is released.

已知的單一服務Well-Known Singleton Services

單一執行個體服務物件的其中一個變化有時可能會很有用處:您可以自行建立服務物件,並建立使用該物件的服務主機。One variation on single instance service objects is sometimes useful: you can create a service object yourself and create the service host using that object. 若要這麼做,您必須同時將 ServiceBehaviorAttribute.InstanceContextMode 屬性設定為 Single ,否則在開啟服務主機時會擲回例外狀況。To do so, you must also set the ServiceBehaviorAttribute.InstanceContextMode property to Single or an exception is thrown when the service host is opened.

請使用 ServiceHost(Object, Uri[]) 建構函式建立此類服務。Use the ServiceHost(Object, Uri[]) constructor to create such a service. 當您想要將特定物件執行個體提供給單一服務使用時,它提供了另一種實作自訂 System.ServiceModel.Dispatcher.IInstanceContextInitializer 的方式。It provides an alternative to implementing a custom System.ServiceModel.Dispatcher.IInstanceContextInitializer when you wish to provide a specific object instance for use by a singleton service. 當您的服務實類型很難以建立時,您可以使用這個多載(例如,如果它不會執行無參數公用的函式)。You can use this overload when your service implementation type is difficult to construct (for example, if it does not implement a parameterless public constructor).

請注意,將物件提供給這個函式時,與 Windows Communication Foundation (WCF)實例行為相關的某些功能會以不同的方式運作。Note that when an object is provided to this constructor, some features related to the Windows Communication Foundation (WCF) instancing behavior work differently. 例如,提供單一物件執行個體時,呼叫 InstanceContext.ReleaseServiceInstance 將沒有任何作用。For example, calling InstanceContext.ReleaseServiceInstance has no effect when a singleton object instance is provided. 同樣的,也會忽略任何其他執行個體的釋放機制。Similarly, any other instance-release mechanism is ignored. ServiceHost 的行為就像是所有作業都已將 OperationBehaviorAttribute.ReleaseInstanceMode 屬性設定為 ReleaseInstanceMode.NoneThe ServiceHost always behaves as if the OperationBehaviorAttribute.ReleaseInstanceMode property is set to ReleaseInstanceMode.None for all operations.

共用 InstanceContext 物件Sharing InstanceContext Objects

您也可以自行執行該關聯,以控制哪個工作階段通道或呼叫應與哪個 InstanceContext 物件產生關聯。You can also control which sessionful channel or call is associated with which InstanceContext object by performing that association yourself.

並行Concurrency

並行是指控制在 InstanceContext 內同時為作用中的執行緒數目。Concurrency is the control of the number of threads active in an InstanceContext at any one time. 這是透過使用 ServiceBehaviorAttribute.ConcurrencyModeConcurrencyMode 列舉型別的方式予以控制。This is controlled by using the ServiceBehaviorAttribute.ConcurrencyMode with the ConcurrencyMode enumeration.

以下為可用的三種並行模式:The following three concurrency modes are available:

  • Single:每一個執行個體內容同時最多可以在執行個體內容中,擁有一個處理訊息的執行緒。Single: Each instance context is allowed to have a maximum of one thread processing messages in the instance context at a time. 其他希望使用相同執行個體內容的執行緒必須封鎖,直到原始的執行緒結束執行個體內容為止。Other threads wishing to use the same instance context must block until the original thread exits the instance context.

  • Multiple:每一個服務執行個體都可以同時擁有多個處理訊息的執行緒。Multiple: Each service instance can have multiple threads processing messages concurrently. 此服務實作必須是安全執行緒,才能使用這種並行模式。The service implementation must be thread-safe to use this concurrency mode.

  • Reentrant:每一個服務執行個體在同一時間內會處理一個訊息,但接受可重新進入 (Re-entrant) 的作業呼叫。Reentrant: Each service instance processes one message at a time, but accepts re-entrant operation calls. 服務只會在透過 WCF 用戶端物件呼叫時,接受這些呼叫。The service only accepts these calls when it is calling out through a WCF client object.

注意

您應該了解,開發能夠安全地使用一個以上之執行緒的程式碼,可能會很難順利地撰寫。Understanding and developing code that safely uses more than one thread can be difficult to write successfully. 在使用 MultipleReentrant 值之前,請確定已適當地設計您的服務以使用這些模式Before using Multiple or Reentrant values, ensure that your service is properly designed for these modes. 如需詳細資訊,請參閱 ConcurrencyModeFor more information, see ConcurrencyMode.

並存的使用與執行個體模式有關。The use of concurrency is related to the instancing mode. PerCall 實例中,並行與不相關,因為每個訊息都是由新的所處理, InstanceContext 因此中不會有一個以上的使用中線程 InstanceContextIn PerCall instancing, concurrency is not relevant, because each message is processed by a new InstanceContext and, therefore, never more than one thread is active in the InstanceContext.

下列程式碼會示範將 ConcurrencyMode 屬性設定為 MultipleThe following code example demonstrates setting the ConcurrencyMode property to Multiple.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class CalculatorService : ICalculatorConcurrency
{
    ...  
}  

與 InstanceContext 設定互動的工作階段Sessions Interact with InstanceContext Settings

工作階段和 InstanceContext 會根據合約內 SessionMode 列舉型別值的組合以及服務實作上的 ServiceBehaviorAttribute.InstanceContextMode 屬性而進行互動,以控制通道與特定服務物件的關聯。Sessions and InstanceContext interact depending upon the combination of the value of the SessionMode enumeration in a contract and the ServiceBehaviorAttribute.InstanceContextMode property on the service implementation, which controls the association between channels and specific service objects.

下表根據服務的 ServiceContractAttribute.SessionMode 屬性與 ServiceBehaviorAttribute.InstanceContextMode 屬性等值的組合,說明支援工作階段或不支援工作階段之傳入通道的結果。The following table shows the result of an incoming channel either supporting sessions or not supporting sessions given a service's combination of the values of the ServiceContractAttribute.SessionMode property and the ServiceBehaviorAttribute.InstanceContextMode property.

InstanceContextMode 值InstanceContextMode value Required Allowed NotAllowed
PerCallPerCall -會話通道的行為:會話與 InstanceContext 每個呼叫的。- Behavior with sessionful channel: A session and InstanceContext for each call.
-無會話通道的行為:擲回例外狀況。- Behavior with sessionless channel: An exception is thrown.
-會話通道的行為:會話與 InstanceContext 每個呼叫的。- Behavior with sessionful channel: A session and InstanceContext for each call.
-無會話通道的行為: InstanceContext 每個呼叫的。- Behavior with sessionless channel: An InstanceContext for each call.
-會話通道的行為:擲回例外狀況。- Behavior with sessionful channel: An exception is thrown.
-無會話通道的行為: InstanceContext 每個呼叫的。- Behavior with sessionless channel: An InstanceContext for each call.
PerSessionPerSession -會話通道的行為:會話與 InstanceContext 每個通道的。- Behavior with sessionful channel: A session and InstanceContext for each channel.
-無會話通道的行為:擲回例外狀況。- Behavior with sessionless channel: An exception is thrown.
-會話通道的行為:會話與 InstanceContext 每個通道的。- Behavior with sessionful channel: A session and InstanceContext for each channel.
-無會話通道的行為: InstanceContext 每個呼叫的。- Behavior with sessionless channel: An InstanceContext for each call.
-會話通道的行為:擲回例外狀況。- Behavior with sessionful channel: An exception is thrown.
-無會話通道的行為: InstanceContext 每個呼叫的。- Behavior with sessionless channel: An InstanceContext for each call.
SingleSingle -會話通道的行為:會話,一個 InstanceContext 用於所有呼叫。- Behavior with sessionful channel: A session and one InstanceContext for all calls.
-無會話通道的行為:擲回例外狀況。- Behavior with sessionless channel: An exception is thrown.
-會話通道的行為:會話以及 InstanceContext 所建立或使用者指定之 singleton 的。- Behavior with sessionful channel: A session and InstanceContext for the created or user-specified singleton.
-無會話通道的行為: InstanceContext 所建立或使用者指定之 singleton 的。- Behavior with sessionless channel: An InstanceContext for the created or user-specified singleton.
-會話通道的行為:擲回例外狀況。- Behavior with sessionful channel: An exception is thrown.
-無會話通道的行為: InstanceContext 每個建立的 singleton 或使用者指定的 singleton 的。- Behavior with sessionless channel: An InstanceContext for each created singleton or for the user-specified singleton.

另請參閱See also