Link to home
Start Free TrialLog in
Avatar of Todd Gerbert
Todd GerbertFlag for United States of America

asked on

Thread Safety .Net C#

Just for the sake of my own edification...I'd appreciate your thoughts.

is the following thread-safe?
public class MyClass
{
	private static readonly int _intValue = 123;
	private static readonly string _stringValue = "one two three";
 
	static MyClass() // Empty static constructor
	{
	}
 
	public MyClass()
	{
                     // instance init
	}
 
	public int IntValue
	{
		get { return _intValue; }
	}
 
	public string StringValue
	{
		get { return _stringValue; }
	}
}

Open in new window

SOLUTION
Avatar of Daniel Wilson
Daniel Wilson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There is only one thraed in your code. there will not be a cross-thread nor deadlock nor race condition.
unsafe Thread might be when there is more than one thread.
Avatar of Todd Gerbert

ASKER

Saed, the question is what if I created a multi-threaded application that created instances of the above class would access to the private static members, via the public properties, be safe?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you all for contributing, very helpful!

(It would seem strings are not quite as immutable as I was led to believe!)
> Thank you all for contributing, very helpful!

you're welcome, glad we could be of some help :)

> (It would seem strings are not quite as immutable as I was led to believe!)

they are indeed not immutable, nor is a private/internal/protected field/method/property really private/internal/protected...

-- Abel --