Question

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

Was it helpful?

Solution

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:

  • The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  • Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

(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.

OTHER TIPS

My question is: Does string concatenation have to be locked?

No, you don't need any locking. MSDN states that System.String is thread-safe (and so are it's methods, including the Format method).

This is not surprising because .Net strings are immutable, meaning it's value cannot be changed after creation. Immutable types are inherently thread-safe because their value cannot be changed by one thread while another thread is also accessing it. If your input parameters were any other reference type that is mutable, then you could run into potential issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top