0

I'm using a concurrentDictionary instance:

private ConcurrentDictionary<string, ConcurrentResource> concurrentResources;

, where:

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

I only want to store a counter for getting how many threads are using the 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;
}

It baffles me that I'm using two threads, and debugging I've realized both threads are performing the lines marked as ************************.

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • Would you mind to provide a working chunk of code to test? – Leonardo Spina Dec 16 '15 at 12:58
  • It's really impossible. There are a lot of code. – Jordi Dec 16 '15 at 13:03
  • 1
    As remarks tells you: [If you call AddOrUpdate simultaneously on different threads, addValueFactory may be called multiple times, but its key/value pair might not be added to the dictionary for every call.](https://msdn.microsoft.com/en-us/library/ee378675(v=vs.110).aspx) – Sebastian Schumann Dec 16 '15 at 14:05

0 Answers0