[問題似乎有點長,但請耐心等待。它有樣品來源問題的解釋]如何在使用多個代理客戶端時修復WCF中的basicHttpBinding?
考慮下面的代碼基本上是一個WCF主持人:
[ServiceContract (Namespace = "http://www.mightycalc.com")]
interface ICalculator
{
[OperationContract]
int Add (int aNum1, int aNum2);
}
[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerCall)]
class Calculator: ICalculator
{
public int Add (int aNum1, int aNum2) {
Thread.Sleep (2000); //Simulate a lengthy operation
return aNum1 + aNum2;
}
}
class Program
{
static void Main (string[] args) {
try {
using (var serviceHost = new ServiceHost (typeof (Calculator))) {
var httpBinding = new BasicHttpBinding (BasicHttpSecurityMode.None);
serviceHost.AddServiceEndpoint (typeof (ICalculator), httpBinding, "http://172.16.9.191:2221/calc");
serviceHost.Open();
Console.WriteLine ("Service is running. ENJOY!!!");
Console.WriteLine ("Type 'stop' and hit enter to stop the service.");
Console.ReadLine();
if (serviceHost.State == CommunicationState.Opened)
serviceHost.Close();
}
}
catch (Exception e) {
Console.WriteLine (e);
Console.ReadLine();
}
}
}
而且WCF客戶端程序是:
class Program
{
static int COUNT = 0;
static Timer timer = null;
static void Main (string[] args) {
var threads = new Thread[10];
for (int i = 0; i < threads.Length; i++) {
threads[i] = new Thread (Calculate);
threads[i].Start (null);
}
timer = new Timer (o => Console.WriteLine ("Count: {0}", COUNT), null, 1000, 1000);
Console.ReadLine();
timer.Dispose();
}
static void Calculate (object state)
{
var c = new CalculatorClient ("BasicHttpBinding_ICalculator");
c.Open();
while (true) {
try {
var sum = c.Add (2, 3);
Interlocked.Increment (ref COUNT);
}
catch (Exception ex) {
Console.WriteLine ("Error on thread {0}: {1}", Thread.CurrentThread.Name, ex.GetType());
break;
}
}
c.Close();
}
}
基本上,我創建10個代理客戶端,然後在單獨的線程上重複調用Add service方法。現在,如果我同時運行的應用程序和用netstat觀察打開的TCP連接,我發現:
- 如果客戶端和服務器的同一臺機器上運行,TCP連接數等於代理對象的數量。這意味着所有請求都是並行服務的。這很好。
- 如果我在一臺單獨的機器上運行服務器,我發現無論創建的代理對象的數量是多少,都會打開最多2個TCP連接。只有兩個請求並行運行。它嚴重傷害了處理速度。
- 如果我切換到net.tcp綁定,一切正常(每個代理對象的一個單獨的TCP連接,即使它們在不同的機器上運行)。
我很困惑,無法讓basicHttpBinding使用更多的TCP連接。我知道這是一個很長的問題,但請幫助!
在配置文件中... – 2010-03-17 10:18:40