Reputation: 438
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
Upvotes: 0
Views: 297
Reputation: 3835
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.
Upvotes: 2
Reputation: 127563
Member assignment of object based classes (which string is one) is atomic in C#. There is no need for the locking at all.
If you had more code other than theMessage = message;
and var msg = theMessage;
in the two blocks it might be needed, but because a single assignment is the only thing you do the locking is unnecessary.
Upvotes: 2