Creating a dictionary in a static class is thread-safe?

So far, I have been developing static classin the C # library, and all methods are clearly static. Any data that is processed is transmitted, so it is thread safe. However, I am implementing a function that requires Dictionaryto count certain line identifiers, which will be generated differently for each thread. Obviously, using something like the following will not be thread safe, because multiple threads will use the same one Dictionaryand ruin its state:

private static readonly Dictionary<string, uint> MyTallies = new Dictionary<string, uint>();

So what is my best option to create this thread safety? As I see it, there are 3 (somewhat bad) options:

  • Make the class non-static; each thread must create a new instance, and a new one can be created for each thread Dictionary. Decreased performance.
  • Put lockaround the code with Dictionaryand clear Dictionaryat the end of the lock. Great performance.
  • Pass Dictionaryeach method that it needs. However, this leads to the fact that it Dictionaryis passed only for an optional function that will not be used most of the time, so it seems that strange code for the calling code should do. Performance also falls because the calling code must instantiate each time Dictionary.

So what is my best option here, or is there another better option that I haven't thought about?

EDIT: simple usage example:

internal static class HtmlFormatter {
    private static readonly Dictionary<string, uint> MyTallies = new Dictionary<string, uint>();

    internal static string RenderHtml(string markdown) {
        string outputHtml = "";

        // (process markdown and render to HTML)
        // (found a heading that requires a unique ID)
        var id = generatedId;
        string unique = "";
        if (MyTallies.ContainsKey(id)) {
            // Already exists; suffix "-x" where x is count of duplicate IDs
            unique = "-" + ++MyTallies[id];
        }
        else {
            MyTallies[id] = 0;
        }
        id += unique;

        // (append id string to HTML output and continue processing)

        return outputHtml;
    }
}
+4
3

. ,

+1

. , , . .

, - , . , .

3 , . ConcurrentDictionary .

1 , . - ? , , .

0

, . , , , .

, .

; , . .

. , .

, . , , . .

, , , . , , , , . (. )

If at the end of all this you need to exchange objects between threads, then there are some useful templates and classes such as ConcurrentDictionary you can use. (thanks Eldar Dordzhiev)

0
source

Source: https://habr.com/ru/post/1629036/


All Articles