Is it thread safe to build strings from local variables using the String
class like in the methods below? Suppose that the methods below are called from several threads.
public static string WriteResult(int value, string name)
{
return string.Format("Result: value={0} name={1}", value, name);
}
public static string WriteResult2(int value, string name)
{
return "Result: value=" + value + " name=" + name;
}
Or do I need to use StringBuilder
to ensure thread safety?
That's absolutely fine. There is no shared state in either piece of code other than the string literals. As strings are immutable, it's fine for strings to be shared freely between threads, and both string.Format
and string.Concat
(implicitly called in the second piece of code) are thread-safe.
Even if one of the parameters were mutable and even if the method mutated the parameters, e.g.
public static void AddResult(int value, List<string> results)
{
results.Add("Value " + value);
}
... then the method itself would still be thread-safe, so long as multiple threads didn't refer to the same List<string>
. If multiple threads did refer to the same List<string>
then it would be unsafe even if it just read from the list, as another thread could be mutating it.
See more on this question at Stackoverflow