2

有人可以解释尽管我将 InstanceContextMode 和 ConcurrencyMode 都设置为单一,并且在 ServiceThrottlingBehavior 中将最大并发调用实例和会话设置为 1,但我仍然发现至少有 2 个线程正在处理 wcf 请求吗?

客户端输出:

Client name :kk Instance:1 Thread:13 Time:2013/12/30 12:17:56
Client name :kk Instance:1 Thread:12 Time:2013/12/30 12:17:57
Client name :kk Instance:1 Thread:13 Time:2013/12/30 12:17:58

服务器代码:

    Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");

    //Create ServiceHost
    ServiceHost host
    = new ServiceHost(typeof(ClassLibrary1.HelloWorldService), httpUrl);

    //Add a service endpoint
    host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService)
    , new WSHttpBinding(), "");

    //Enable metadata exchange
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    ServiceThrottlingBehavior stb = new ServiceThrottlingBehavior
    {
        MaxConcurrentCalls = 1,
        MaxConcurrentInstances = 1 ,
        MaxConcurrentSessions = 1
    };
    host.Description.Behaviors.Add(smb);
    host.Description.Behaviors.Add(stb);
    //Start the Service
    host.Open();

客户代码:

    ServiceReference1.HelloWorldServiceClient obj = new ServiceReference1.HelloWorldServiceClient();
    for(int i=0;i<15;i++)
    {
       obj.Call(str);
       Thread.Sleep(1000);
    }

服务代码:

[ServiceContract]
public interface IHelloWorldService
{
    [OperationContract(IsOneWay=true)]
    void Call(string ClientName);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
    public static int i;

    public HelloWorldService()
    {
        i++;
    }
    public void Call(string ClientName)
    {
        Console.WriteLine("Client name :" + ClientName + " Instance:" + i.ToString() + " Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + " Time:" + DateTime.Now.ToString() + "\n\n");
    }

}
4

2 回答 2

4

我不是线程方面的专家,但我会对此进行尝试并扩展我的评论。

根据 MSDN,ConcurrencyMode.Single意味着The service instance is single-threaded and does not accept reentrant calls. If the InstanceContextMode property is Single, and additional messages arrive while the instance services a call, these messages must wait until the service is available or until the messages time out.

您在每次连续调用之间延迟 1 秒来调用您的服务。您的输出也显示了这一点 - 每个呼叫都比前一个呼叫晚 1 秒。

我相信在这种情况下线程 id 是一个红鲱鱼,因为我希望该服务使用线程池中的可用线程。我在文档中看不到任何保证每次都使用同一个线程的内容,在我看来,这将是一个不合理的期望。

如果您希望从可用线程中获得专用线程,我认为您无法做到这一点。如果您希望该服务一次只处理一个请求,那么您拥有它的方式应该这样做。

于 2013-12-30T05:31:01.353 回答
1

我同意蒂姆的回答即不需要为所有呼叫提供服务。将只保证一个线程一次ConcurencyMode.Single为调用提供服务。

如果由于某种原因您需要 WCF 服务上的线程关联,例如,如果您在 WinForms/WPF 应用程序上运行单例服务,并且您希望服务调用仅在 UI 线程上运行 - 那么,您只Open需要UI线程上的服务主机。WCFSynchronizationContext知道并且只会将调用调度到 UI 线程,而不管您ConcurrencyMode是什么。另请参阅属性的UseSynchronizationContextServiceBehavior属性。

于 2013-12-30T05:56:50.320 回答