ConcurrentDictionary在C#中不是线程安全的

时间:2015-12-16 12:57:02

标签: c# multithreading

我正在使用concurrentDictionary实例:

private ConcurrentDictionary<string, ConcurrentResource> concurrentResources;

,其中:

private class ConcurrentResource
{
     private int counter;
     private FlexLucene.Index.IndexWriter writer;
}

我只想存储一个计数器,以获取使用IndexWriter的线程数。

private FlexLucene.Index.IndexWriter toggleIndexWriter(System.IO.DirectoryInfo directory)
{
    IndexEngine.ConcurrentResource concurrentResource = this.concurrentResources.AddOrUpdate(
        directory.FullName,
        (directoryPath) =>
        {
            ********************************
            FlexLucene.Index.IndexWriter writer = this.createIndexWriter(directoryPath);   
            return new IndexEngine.ConcurrentResource(writer);
            ********************************
        },
        (directoryPath, internalConcurrentResource) =>
        {
            if (!internalConcurrentResource.Writer.IsOpen())
                internalConcurrentResource.Writer = this.createIndexWriter(directoryPath);

            internalConcurrentResource.Counter += 1;
            return internalConcurrentResource;
        }
    );

    return concurrentResource.Writer;
}

令我感到困惑的是,我正在使用两个线程,并且调试我已经意识到两个线程都在执行标记为************************的行。

有什么想法吗?

0 个答案:

没有答案