WCF ConcurrencyMode Single和InstanceContextMode PerCall

max*_*e51 20 c# wcf wcf-configuration servicebehavior

我的wcf服务配置有问题.我希望每次调用我的服务都会创建一个新的服务实例.对于并发性,我希望一次调用在另一次启动之前完成.

因此,如果我有这样的服务:

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single,
InstanceContextMode=InstanceContextMode.PerCall)]
public class MyService: IMyService
{
    public bool MyServiceOp()
    {
        Debug.WriteLine("thread "+ 
            Thread.CurrentThread.ManagedThreadId.ToString());
        Debug.WriteLine("start operation ");
        Do_work()
        Debug.WriteLine("end operation");
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在循环中调用多个调用时,跟踪给出:

thread 1
thread 2
start operation
start operation
end operation
end operation
Run Code Online (Sandbox Code Playgroud)

虽然我想这样:

thread 1 start operation end operation
thread 2 start operation end operation
Run Code Online (Sandbox Code Playgroud)

这可能吗?谢谢

Ern*_*ieL 20

我知道这个问题被标记为已回答,但有一个更好的选择:

如果您使用InstanceContextMode.Single,那么您将为所有调用重用相同的实例.如果您的服务长期运行,则需要您的代码完美地管理资源,因为如果没有重新启动服务,它将永远不会被垃圾收集.

而是保持InstanceContextMode.PerCall"每次调用我的服务创建一个新实例",然后使用限制:最大并发实例设置为1.MSDN文档正是这样做的一个例子.


Pat*_*ars 5

你所拥有的将导致每个请求启动一个新的服务实例(这就是PerCall所做的).

这应该这样做:

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single, InstanceContextMode=InstanceContextMode.Single)]
Run Code Online (Sandbox Code Playgroud)

仅供参考,如果你这样做,你将失去所有的可扩展性.您将拥有一个单线程服务实例来响应所有请求.