多线程WCF服务中的高效集合维护

时间:2012-04-05 13:59:24

标签: c# multithreading wcf synchronization

我们有一个简单的WCF服务,用InstanceContextMode = Single和ConcurrencyMode = Multiple标记。对于返回列表的方法,我们只需返回列表的本地副本,而不是在调用时转到我们的数据库并填充列表。该列表由后台线程维护,该后台线程每24小时发送到我们的数据库并重新填充列表。我们通过在2个位置锁定对象来处理并发问题:返回集合的方法内部以及填充集合的方法内部。

我的问题是,我们如何才能提高效率。目前,我们在客户端将调用的服务方法“GetCustomers”中存在瓶颈:

public List<ZGpCustomer> GetCustomers()
{
    List<ZGpCustomer> customerListCopy = new List<ZGpCustomer>();
    lock (_customerLock)
    {
        customerListCopy = new List<ZGpCustomer>(_customers);
    }

    return customerListCopy;
}

由于“_customers”仅在每24小时填充一次,因此我们应该只在修改集合时才需要锁定GetCustomers方法。它当前设置的方式,如果1000个请求同时进入,我们实际上是排队1000个请求,因为一次只有一个线程可以访问该方法。这使得服务的多线程方面有些无用,不是吗?

这种模式是否有最佳实践?我应该使用更合适的数据集来存储我的对象吗? “BlockingCollection”会更合适吗?

1 个答案:

答案 0 :(得分:2)

当然,这是一种更有效的方式。诀窍是保持对集合的主引用不可变。这样你就不必在阅读器端同步访问。只有作家方面需要锁定。读者方面不需要任何东西,这意味着读者保持高度并发。您唯一需要做的就是将_customers引用标记为volatile。

// Variable declaration
object lockobj = new object();
volatile List<ZGpCustomer> _customers = new List<ZGpCustomer>();

// Writer
lock (lockobj)
{
  // Create a temporary copy.
  var copy = new List<ZGpCustomer>(_customers);

  // Modify the copy here.
  copy.Add(whatever);
  copy.Remove(whatever);

  // Now swap out the references.
  _customers = copy;
}

// Reader
public List<ZGpCustomer> GetCustomers()
{
    return new List<ZGpCustomer>(_customers);
}

如果您愿意稍微更改GetCustomers的签名,则可以利用_customers的不变性并返回只读包装。

// Reader
public IList<ZGpCustomer> GetCustomers()
{
    return _customers.AsReadOnly();
}