0

Forgive me but I'm not quite sure where in my code things are going wrong! I'm working on creating a multithreaded tcp server, and am attempting to store strings using a dictionary. The code looks like this:

class Echo : Iprotocol
{
    public Dictionary<string, string> dictionary = new Dictionary<string, string>();
    private const int BUFFSIZE = 32; //buffer size

    private Socket client_sock; //Socket
    private Ilogger logger; // logger

    public Echo(Socket sock, Ilogger log)
    {
        this.client_sock = sock;
        this.logger = log;
    }
    public string handlewhois(string inname)
    {
        ArrayList entry = new ArrayList();
        string name = inname;
        string message = null;
        if (dictionary.ContainsKey(name) == true)
        {
            entry.Add(System.DateTime.Now + "Dictionary reference found at thread: " + Thread.CurrentThread.GetHashCode());
            message = dictionary[name];
        }
        else
        {
            entry.Add(System.DateTime.Now + "Dictionary reference not found at thread:  " + Thread.CurrentThread.GetHashCode());
            message = "ERROR: no entries found";
        }
        logger.writeEntry(entry);
        return message;
    }
    public string handlewhois(string inname, string inlocation)
    {
        ArrayList entry = new ArrayList();
        string name = inname;
        string location = inlocation;
        string message = null;
        entry.Add(System.DateTime.Now + "Dictionary reference created or updated at thread: " + Thread.CurrentThread.GetHashCode());
        dictionary.Add(name, location);
        message = "OK";
        logger.writeEntry(entry);
        return message;
    }
}

It runs perfectly fine, however as I step through it in debug, I see the the dictionary entry created, however when it gets to the line: logger.writeEntry(entry);

It suddenly vanishes, with dictionary not containing any values.

I think it may have something to do with the multithreading but honestly I have no idea!

Bridge
  • 29,818
  • 9
  • 60
  • 82

1 Answers1

2

Dictionary is not thread safe - please consider using ConcurrentDictionary instead.

From the Dictionary documentation:

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

For a thread-safe alternative, see ConcurrentDictionary.

Public static (Shared in Visual Basic) members of this type are thread safe.

See this SO question and answer for more information.

Community
  • 1
  • 1
Bridge
  • 29,818
  • 9
  • 60
  • 82