2011-05-19 64 views
3

我想了解ServiceBehavior.ConcurrencyMode屬性。瞭解WCF ServiceBehaviorProperty併發模式

考慮在服務端下面的代碼:

[ServiceContract] 
public interface IMySercice { 
    [OperationContract] 
    int mycall(int a); 
} 
/*** HERE I WILL GENERATE Two variants of this code ***/ 
[ServiceBehaviour(InstanceContext = InstanceContextMode.Single)] 
public class MyService : IMyService { 
    // Constructors... 
    // implementations of interface 
    public int mycall(int a) { ... } 
} 
class Program { 
    static void Main(string[] args) { 
     MyServiceMyS = new MyService(...); /* Creating service instance */ 
     Uri MyUri = new Uri("http://services.mycompany.com/services/"); /* Base address for my hosted service */ 
     using (ServiceHost host = new ServiceHost(MyS)) { /* Defining service host, configuration file contains info regarding endpoints, not shown here for clarity */ 
     host.Start(); 
     host.Stop(); 
     } 
    } 
} 

現在考慮,我想調用此服務,請考慮可能調用我的服務網絡10臺機器。 在某一點上,它發生這10臺機器全部同時請求int mycall(int a) 10個請求。 我想,以檢查這些場景:

方案1

... 
/*** VARIANT 1 ***/ 
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContext = InstanceContextMode.Single)] 
public class MyService : IMyService { 
    ... 
} 
... 

方案2

... 
/*** VARIANT 2 ***/ 
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContext = InstanceContextMode.Single)] 
public class MyService : IMyService { 
    ... 
} 
... 

所以,10個併發呼叫到達...是什麼在這兩種情況下發生?請告訴我,我是對還是錯:

在場景1中,單線程,這10個調用一次排隊並執行一個。我的服務(我的服務的相同實例)的方法將依次被調用十次。在場景2中,多線程的WCF將導致10個線程同時調用我的服務方法。

這是我說的嗎? 謝謝

+0

在這兩種情況下,您的代碼都不會編譯,因爲'ServiceHost'既沒有'Start()'也沒有'Stop()'方法。 – 2011-05-20 21:01:00

回答

6

在這兩種情況下,所有10個客戶端將由10個不同的線程並行服務。原因是ConcurrencyMode設置依賴於InstanceContextMode設置。 InstanceContextMode定義了WCF引擎服務器的客戶端請求 - 是如何創建的服務的新實例,如果請求到達時:

  • PerCall - 從單一代理的所有要求 - 每個請求由服務
  • PerSession的新實例提供服務例如由相同的服務實例
  • Single服務 - 每臺主機的單 - 所有的請求是由相同的服務實例服務

所以你的描述是正確的,如果您還使用InstanceContextMode.Single但默認值是PerCall的(NetTcpBinding的,netNamedPipeBinding,的wsHttpBinding在默認配置中使用的安全上下文)綁定不支持會話(basicHttpBinding的,的WebHttpBinding,的wsHttpBinding沒有安全上下文或可靠的會話)的綁定支持會話或PerSession

ConcurrencyMode定義瞭如果多個請求想要訪問服務的實例,如何使用該服務的實例。例如PerCallMultiple併發性的實例化與Single併發性相同,因爲無論併發設置如何,每個實例都只用於服務一個請求。

+0

謝謝Ladislav,我編輯了指定Singel的代碼爲InstanceCOntextMode,我很抱歉沒有這樣做過......我想現在我的描述是正確的吧?提前致謝。 – Andry 2011-05-20 17:26:22

+0

是的,如果你有單身服務,你的描述應該是正確的。 – 2011-05-31 08:40:06

0

是的,使用InstanceContextMode.Single你所描述的應該是你應該看到的行爲。超過10個同時通話,你實際上仍然會得到相同的行爲,因爲在服務的ServiceThrottlingBehavior(「會話」)上,你會達到MaxConcurrentSessions的默認限制值10,只要限制行爲是通道可以一次打開)。