sooqua sooqua - 1 month ago 16
C# Question

ReaderWriterLockSlim and references

I have a class:

public static class Message
{
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
private static string theMessage;

public static void SetMessage(string message)
{
Locker.EnterWriteLock();
theMessage = message;
Locker.ExitWriteLock();
}

public static string GetMessage()
{
Locker.EnterReadLock();
var msg = theMessage; // <<<=====
Locker.ExitReadLock();
return msg;
}
}


If I understand correctly, in the pointed line I'm creating a reference to
theMessage
, and then returning it. Multiple threads will then access the same variable, or I'm wrong?

Do I need to call
string.Copy
instead to make sure it is thread safe?

Thanks

Answer

Because string is a reference type you are getting the refernce to a value and not the value itself in this line:

var msg = theMessage;

If you want to prevent changes from other threads to affect the return value of the method for most of the refernce types I would suggest you to copy the value and return another reference to the new copied value.
But string is immutable type so it doesn't really matter because anyway other threads can't change it's value (no one can it is immutable!).

So no you do not have to deep copy the string to prevent other threads from changing the return value.

You can refer these questions(1,2) for further reading why immutable objects are thread safe.