我讀了很多關於wcf併發和實例上下文模式的文章,我也閱讀了CodeProject的文章,但仍然無法使其工作。這是我的客戶端代碼(如果你問我爲什麼使用實例上下文,那是因爲我最終會測試回調函數,但是我還沒有,只是嘗試多次同時執行一個簡單的請求/響應)WCF ConcurrencyMode多個不能正常工作
public void Run()
{
InstanceContext context = new InstanceContext(this);
MyServiceReference.MyService service = new MyServiceReference.MyService(context);
for (int i = 0; i < 10; i++)
{
int j = i;
Thread t = new Thread(() => myFun((j + 1), service));
t.Start();
}
countdownEvent.Wait();
Console.ReadLine();
service.Close();
}
private void myFun(int threadNo, MyServiceReference.MyServiceClient service)
{
Console.WriteLine(service.GetData1(threadNo));
countdownEvent.Signal();
}
這是該服務的代碼:
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
public interface IMyService
{
[OperationContract]
string GetData1(int value);
}
public interface IMyServiceCallback
{
[OperationContract]
string GetData2(int value);
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext=false)]
public class MyService : IMyService
{
public string GetData1(int value)
{
reponse = DateTime.Now.ToString();
Thread.Sleep(5000);
return "Request: " + value + ", Thread id: " + Thread.CurrentThread.ManagedThreadId + ", response: " + reponse;
}
這是輸出:
Request: 1, Thread id: 9, response: 2015-08-14 11:39:42
Request: 2, Thread id: 10, response: 2015-08-14 11:39:47
Request: 3, Thread id: 8, response: 2015-08-14 11:39:52
Request: 4, Thread id: 9, response: 2015-08-14 11:39:57
Request: 5, Thread id: 10, response: 2015-08-14 11:40:02
Request: 6, Thread id: 9, response: 2015-08-14 11:40:07
Request: 7, Thread id: 10, response: 2015-08-14 11:40:12
Request: 8, Thread id: 9, response: 2015-08-14 11:40:17
Request: 9, Thread id: 10, response: 2015-08-14 11:40:22
Request: 10, Thread id: 9, response: 2015-08-14 11:40:27
我期望將ConcurrencyMode設置爲多個會使請求通過使用多個線程同時運行,但即使我看到3個線程使用,操作仍然按順序執行(每個響應之間5秒),我錯過了什麼?
我看到的每個例子都是使用void return和IsOneWay = True的操作,這就是爲什麼它不適合我嗎? 但是,我在每個請求的客戶端上使用不同的線程,因此即使每個線程都在等待自己的響應,所有請求都應該同時完成。
我在WCF服務主機和NetTcpBinding調試運行,可以運行在調試影響併發?
我認爲這可能是由於使用相同的服務客戶。默認情況下會話已啓用,因此它可能只是作爲同一會話的一部分依次執行它們。你可以嘗試把SessionMode.NotAllowed放在你的服務行爲上嗎? – Juan
SessionMode在ServiceContract屬性上不行爲,但無論如何,似乎我無法關閉與netTcpBinding的會話。 爲什麼同一個客戶端會話無法完成同時請求? – Jonathan
我嘗試過使用許多不同的客戶端,它按預期工作(請求同時執行),但如果我想使用同一個客戶端呢?不可能? – Jonathan