0

I have a dictionary which I want to make it static. For suppose I have a dictionary which has some data.If I am accessing this dictionary by two processes at the same time then my data mismatches. How can I solve this problem.

for example In a dictionary I have key A- values 1 2 3 4 5 key B- values 6 7 8 9 10

When I am accessing this dictionary by two processes one reads data for A and other reads data for B. Then I have results sets where B contains A values.

A.Alessio
  • 321
  • 2
  • 15
user679530
  • 897
  • 1
  • 8
  • 11
  • 3
    Rather than start an endless stream of "If your program is written in ..." answers, why don't you tell us which programming language you are writing it in? – thkala Apr 08 '11 at 21:16
  • ...and remember to say in future questions too! – Tom W Apr 08 '11 at 21:34

3 Answers3

1

You just need to use a ConcurrentDictionary, in System.Collections.Concurrent

private static readonly ConcurrentDictionary<TKey, TValue> dictionary = 
    new ConcurrentDictionary<TKey, TValue>();
Alexandre TRINDADE
  • 917
  • 10
  • 21
0

If your program is written in Java, you need to synchronize any methods that retrieve and set the values.

For example:

public synchronized int getValue() {
    return value;
}

The 'synchronized' keyword ensures that two processes do not read or set data concurrently.

This is achieved by the JVM acquiring a lock on the object, to only allow one thread to access it at a time. The code is then executed, and once completed the lock is released. If another thread is waiting, this thread can then acquire a lock on the object.

Tom W
  • 578
  • 6
  • 16
0

If your program is written in .NET, you can take a look at this related question regarding the best way of implementing a thread-safe Dictionary, with links and C# sample code…

Community
  • 1
  • 1
mousio
  • 10,079
  • 4
  • 34
  • 43