sooqua sooqua - 4 years ago 178
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)
theMessage = message;

public static string GetMessage()
var msg = theMessage; // <<<=====
return msg;

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

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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download