简体   繁体   English

WCF服务的多个应用程序域导致并发问题

[英]WCF Service's Multiple App Domains Causing Issues With Concurrency

I have a WCF Service Endpoint that is defined with the following ServiceBehavior attribute. 我有一个WCF服务端点,它使用以下ServiceBehavior属性定义。

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

I am having issues with a call within my service that needs to guarantee that an object is only created once. 我的服务中的调用存在问题,该调用需要保证一个对象仅创建一次。 The following code is called within my service. 在我的服务中调用了以下代码。

public class MySingletonDataProvider{
     private static MySingletonDataProvider _instance;
     private static readonly object _lock = new object();

     public static MySingletonProvider Create(){

          lock(_lock){

              if(_instance == null){
                 _instance = new MySingletonProvider();
                 Log.Info("New Instance Created " + AppDomain.CurrentDomain.FriendlyName");
              }

              return _instance;
          }
     }
}

When this is hit, we are typically getting 3-5 logs such as the following: 遇到这种情况时,通常会收到3-5个日志,例如:

- "New Instance Created 123252352323623"
- "New Instance Created 423523562362362"
- "New Instance Created 235623623462366"

Showing that multiple AppDomains are able to execute the code within the lock. 显示多个AppDomain能够执行锁中的代码。 This is causing huge issues. 这引起了巨大的问题。 What is the solution so that I can guarantee that this instance is only created once? 有什么解决方案,以便可以保证只创建一次该实例?

CLR creates new MySingletonDataProvider instance for each AppDomain, thus you have separate locking objects. CLR为每个AppDomain创建新的MySingletonDataProvider实例,因此您具有单独的锁定对象。 I'd suggest to use some kind of inter-process synchronization primitives, as mutexes, for example. 我建议使用某种进程间同步原语,例如互斥体。 http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx http://msdn.microsoft.com/zh-CN/library/system.threading.mutex.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM