本文介绍了抵御竞争条件在System.Collections.Concurrent.ConcurrentDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET ConcurrentDictionary是容易的竞争条件,可能会在导致意外的数据解释这个MSDN文章的底部。我假设有几个因素要考虑。

The .NET ConcurrentDictionary is susceptible to a race condition that may cause unexpected data as explained at the bottom of this MSDN article. I'm assuming that there are several factors to take into account.

问:我应该怎么写code,是不是容易受到竞争情况,可能会导致数据丢失。

Q: How should I write code that is not vulnerable to that race condition that may cause data loss?

在我的情况我有了一个始终增加折射率(n ++)的输入流。我的想法是,我可以检测丢失数据如果比赛条件且重新发送。而另一方面,有可能是一个更好的办法做到这一点,我不知道。

In my scenario I have an input stream that has an always increasing index (n++). My thought is that I could detect missing data if the race condition occurs and re-send it. On the other hand, there may be a better way to do this that I'm unaware of.

推荐答案

有并发集合(不限于.NET)的一般缺陷,人们必须意识到,这是个人操作可能会线程安全的,但操作序列不是原子。我的意思是以下几点:假设这种情况下,我在那里有一个并发收集了检查添加运行,无论是原子的。

There is a general pitfall with concurrent collections (not limited to .net) that people have to be aware of, which is that individual operations may be thread-safe, but sequences of operations are not atomic. What I mean by this is the following: assume this scenario, where I have a concurrent collection with a Check and an Add operation, both atomic.

我想要做的是检查是否存在某个值,如果没有,添加它。因此,我可以这样写:

What I want to do is check if a value exists and if not, add it. So I can write this:

if(!collection.Check(value))
{
    collection.Add(value);
}

虽然这两个操作都是原子的,上面的序列不是,作为一个线程可以被校验和的添加通过另一个线程,这导致不一致的结果之间中断。因此,整个序列应通过包装在一个锁定语句,例如制成原子弹。

Although both operations are atomic, the above sequence is not, as a thread may be interrupted between the check and the add by another thread, which leads to inconsistent results. Thus, the entire sequence should be made atomic by wrapping it in a lock statement for example.

lock(locker)
{
   if(!collection.Check(value))
   {
       collection.Add(value);
   }
}

这篇关于抵御竞争条件在System.Collections.Concurrent.ConcurrentDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:10