I'm calling a simple string concatenation function from multiple threads . I locked it as I think should. Made many tests with lock or without lock. It never failed.
My question is: Does string concatenation have to be locked?
private readonly object idLock = new object();
private string GetId(string input1, string input2, string input3)
{
lock (idLock)
return string.Format("{0}; {1}; {2}", input1, input2, input3);
}
I tested the following variants with PLINQ - 10000000 cycles. Time in milliseconds is:
// Time 5446
lock (idLock)
return string.Format("{0}; {1}; {2}", input1, input2, input3);
// Time 3728
lock (idLock)
return input1 + "; " + input2 + "; " + input3;
// Time 953
return string.Format("{0}; {1}; {2}", input1, input2, input3);
// Time 652
return input1 + "; " + input2 + "; " + input3;
Full test code is here: Test Parallel String Concatenation
No, it does not have to have any locking constructs.
Any pure method will function just fine in a multithreaded environment.
By "pure" I mean a method that:
(source: Wikipedia: Pure Function)
In your case, string concatenation by itself is fine in a multithreaded environment and does not need any locking constructs.
However, if you're concatenating strings that you read from fields or properties that can be changed by other threads, then you will need locking or similar to ensure the stability of your system, but the example code in your question, no.