2012-09-21 75 views
5

我已經爲WCF實現了REST服務。該服務提供了一個功能,可以由許多客戶端調用,並且此功能需要1分多鐘才能完成。所以我想要的是,對於每個客戶端,都會使用一個新對象,以便一次處理多個客戶端。WCF REST服務:InstanceContextMode.PerCall不工作

我的界面看起來是這樣的:

[ServiceContract] 
public interface ISimulatorControlServices 
{ 
    [WebGet] 
    [OperationContract] 
    string DoSomething(string xml); 
} 

而且(測試)實現它:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall] 
public class SimulatorControlService : SimulatorServiceInterfaces.ISimulatorControlServices 
{ 
    public SimulatorControlService() 
    { 
     Console.WriteLine("SimulatorControlService started."); 
    } 

    public string DoSomething(string xml) 
    { 
     System.Threading.Thread.Sleep(2000); 
     return "blub"; 
    } 
} 

現在的問題是:如果我使用的是創建10個客戶端(或任何號碼)線程,每個線程調用服務,它們不會同時運行。這意味着,這些電話正在一個接一個地處理。有人知道爲什麼會發生這種情況嗎?

新增:客戶端代碼

產卵線程:

 for (int i = 0; i < 5; i++) 
     { 
      Thread thread = new Thread(new ThreadStart(DoSomethingTest)); 
      thread.Start(); 
     } 

方法:

提前
private static void DoSomethingTest() 
    { 
     try 
     { 
      using (ChannelFactory<ISimulatorControlServices> cf = new ChannelFactory<ISimulatorControlServices>(new WebHttpBinding(), "http://localhost:9002/bla/SimulatorControlService")) 
      { 
       cf.Endpoint.Behaviors.Add(new WebHttpBehavior()); 

       ISimulatorControlServices channel = cf.CreateChannel(); 

       string s; 

       int threadID = Thread.CurrentThread.ManagedThreadId; 

       Console.WriteLine("Thread {0} calling DoSomething()...", threadID); 

       string testXml = "test"; 

       s = channel.StartPressureMapping(testXml); 

       Console.WriteLine("Thread {0} finished with reponse: {1}", threadID, s); 
      } 

     } 
     catch (CommunicationException cex) 
     { 
      Console.WriteLine("A communication exception occurred: {0}", cex.Message); 
     } 
    } 

謝謝!

+0

你是如何產卵客戶端的請求?你能給出一些代碼嗎?請注意,您可以編輯您的問題以添加詳細信息。 – Jeroen

+0

添加了客戶端代碼。 – Cleo

+0

如果您的服務不使用共享資源,則可以將ServiceBehavior更改爲Single with Concurrency Multiple。這會給你一個服務實例,它是多線程的(每次調用一個線程)。 '[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = ConcurrencyMode.Multiple)]' – JanW

回答

1

由於服務是由GUI控制,需要在「UseSynchronizationContext」屬性來解決這個問題:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)]