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 = "";
var id = generatedId;
string unique = "";
if (MyTallies.ContainsKey(id)) {
unique = "-" + ++MyTallies[id];
}
else {
MyTallies[id] = 0;
}
id += unique;
return outputHtml;
}
}