user12081736
user12081736

Reputation:

Is Dictionary of ConcurrentQueue threadsafe?

I am writing log class for my c# program. Multiple threads will be enqueuing data, only one will be dequeuing. Is my code thread safe now or should I use ConcurrentDictionary or ImmutableDictionary?

Keys wont be added/deleted, I'm using only Enqueue and TryDequeue functions. Which container is the fastest for this kind of work?

        public static readonly Dictionary<string, ConcurrentQueue<string>> Logs = new Dictionary<string, ConcurrentQueue<string>>()
        {
            {"Info", new ConcurrentQueue<string>() },
            {"Warn", new ConcurrentQueue<string>() },
            {"Error", new ConcurrentQueue<string>() }
        };

        public static void Add(string type, string content)
        {
            if (type == "Info") Logs["Info"].Enqueue(content);
            else if (type == "Warn") Logs["Warn"].Enqueue(content);
            else if (type == "Error") Logs["Error"].Enqueue(content);
        }

        public static void Save()
        {
            while (true)
            {
                //dequeuing and saving data to file
            }
        }

Upvotes: 0

Views: 386

Answers (1)

xxbbcc
xxbbcc

Reputation: 17327

To signal to other developers that your dictionary is read-only, use ReadOnlyDictionary<T1, T2> instead. This prevents you from making changes to the dictionary itself. Since the items in the dictionary are already thread-safe (ConcurrentQueue), the rest of your code should be fine.

For example:

using System.Collections.Generic;
using System.Collections.ObjectModel;

...

public static readonly ReadOnlyDictionary<string,
    ConcurrentQueue<string>> Logs = CreateLogMap();

...

private static ReadOnlyDictionary<string, ConcurrentQueue<string>> CreateLogMap()
{
    var map = new Dictionary<string, ConcurrentQueue<string>>()
    {
        {"Info", new ConcurrentQueue<string>() },
        {"Warn", new ConcurrentQueue<string>() },
        {"Error", new ConcurrentQueue<string>() }
    };

    return (new ReadOnlyDictionary<string, ConcurrentQueue<string>>(map));
}

Upvotes: 2

Related Questions