I'm coming from an obj-c background looking at some C# code. In a partial subclass of Window, I see this at the top of the code:
public partial class MyMessage : Window
{
private static object _messageLock = new object();
private static MyMessage _f = new MyMessage();
What are these types of member variables used for? I know you can create a static variable for a class so that it is used for the whole class (the classic example being some int count variable that will increment every time the class is instantiated in order to keep track of how many objects of that class are instantiated). In this case, I am not sure what it means.
Thanks.
private static object _messageLock = new object();
private static MyMessage _f = new MyMessage();
This looks like the class creates a Singleton of type MyMessage and then controls access to it using a lock on the messageLock variable - hard to verify though without the full code.
Well i can answer what the first member is used for. This is for creating a thread lock. One object which is used to mark which thread currently holds the lock and can do his business. I guess the second member is used for threading aswell, but without the rest of the code its difficult to answer.
So these two members are privat static which means only one instance of these variables no matter how many MyMessage objects are created and can only be accessed inside MyMessage instances.
These static member variables store things that are scoped to be available to every object created from that class - so one variable shared amongst 0 to many objects. These are private, so they are only available to code from within the class.
The _messageLock looks like its probably intended to be an object used in a lock() statement, somewhere in the class there is probably:
lock(_messageLock)
{
// some code
}
Or somethign using some other form of thread-safe lock. This is intended to create some form of 'one thread only' portions of the code.
Combined witht the static MyMessage - I'm guessing this is a form of singleton. There are a number of different C# singleton patterns discussed in this MSDN article
I think what you are asking is simply 'What is a static field', not 'What are the specific private static fields doing here' like everyone else seems to be answering.
A private static member variable such as the ones in your example are private member variables that can be accessed by ANY object of that class. Any instance you create of MyMessage will be able to access those member variables.
It seems that MyMessage is a singleton class, and it internally manages a private variable called _f which is actually the singleton instance.
And from the name, it guess that _messageLock is used in lock statement, to protect critical code section, (such as in multithreaded application), as:
lock(_messageLock)
{
//critical section
}
Have a look at : lock Statement (C# Reference) at MSDN
Related
I am building an application in ASP.NET MVC 4. I am creating a class (similar to Factory type) that will return me instance of my service classes which i have made in BAL Layer. I want to declare static properties in that class and they should return Instance of requested Service Class.
My question is that is it possible that a static propery will return instance of new class because static property will be allocated a memory that will remain throughout the application. I am little confused here, Please explain what happens and what is best way to do so.
Code done so far
public class Factory
{
public static CountryService CountryServiceInstance
{
get
{
return new CountryService(new CountryRepository());
}
}
}
What you should do is write a function the will create the new instances not a get property
public class Factory
{
public static CountryService CreateNewService()
{
return new CountryService(new CountryRepository());
}
}
About your memory concern read Sriram Sakthivel's first comment
More about the Factory pattern here:
http://msdn.microsoft.com/en-us/library/ee817667.aspx
A property in C# is just a method which returns what it should return in its body. In your case, each time you access that property, a new instance of the service will be created.
In case you want only one instance of that service, you might want to store it to the static private variable like this
private static readonly Lazy<CountryRepository> _fact
= new Lazy<CountryRepository>(() => new CountryRepository());
Also, a static properlty never stores something "in the memory throughout the application", but a programmer can do that.
Once again, a property is just a pair of set\get methods, unless you use an automatic property, where there is also a backing field created for the value to store.
A static keyword itself only specifies that a current class member must not be accessed though this keyword, and its value will be shared all across the appdomain (or your application).
your method CountryServiceInstance for each call will always gives you a new instance of CountryRepository.
As you have mentioned, Most of the Factory classes are static which are responsible for creating new object instances. If they give the same object instance none of the factory patterns will serve its intent.
you can undoubtedly proceed with your sinppet..
if you want to quickly validate you can check the created objects hashcode
object.GetHashCode() they will be unique as they are separate objects
I am trying to set the following public var:
var collection = new Dictionary<string, Statistics>();
I want to be able to use the same collection all through my application and i therefore want to create it right at the top when the applications starts.
How would i do this?
There is no concept of a global variable in C#. You always have to declare variable inside some class/scope.
What you can do, is to make it accessible via public modifier, like a property (say).
Just an idea:
public class Shared
{
public Dictionary<string, Statistics> CollectionDic {get;set;}
public Shared() {
CollectionDic = new Dictionary<string, Statistics>();
}
}
After you can access it like:
var shared = new Shared();
shared.CollectionDic.Add(..)
...
You have to workout by yourself, what fits your exact needs.
You can create it as a public static field or property in public class (optionally also static):
public class Variables
{
public static Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();
}
Then access it in code:
Variables.collection.Add(...);
Note that it is not thread-safe approach. So if you intend to use static dictionary in multithreading app, it's better to either have static methods, wraping the dictionary in thread-safe way (as Jon Skeet mentioned) or use thread-safe collections, for exapmle ConcurrentDictionary.
The error you are getting is:
The contextual keyword 'var' may only appear within a local variable
declaration
I believe you are trying to define your collection as:
public partial class Form1 : Form
{
var collection = new Dictionary<string, Statistics>();
You can't use var keyword at this level,
I want all of my Form1.cs to access it, not different .cs files
You may define it like:
Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();
It will be available to all the methods inside the Form1 class
EDIT
The comments of the OP showed, that the requirement is only to be able to access the variable through the one .cs code. Please disregard the following, and please vote delete if you think that this answer is not a valuable addition to the question for future visitors of this topic. Or vote up, if you think it has enough added value to stay.
What I meant for the original question, regarding I want to be able to use the same collection all through my application
In an object oriented environment, if this is a requirement that can not be surpassed by refactoring/restructuring the application, you should definitely use the Singleton design pattern
A singleton is a pattern, which guarantees that only one instance of the given class exists (per application contex/virtual machine, of course), and that that instance can be accessed from everywhere in the context of the same application.
That is:
create a class (e.g. by name MyDictionary)
implement the necessary functions you want from it (you want this to be independent of the underlying implementation)
make it a singleton by following the article
decide if you need lazy loading
I'd recommend to always use thread safe implementation when dealing with singletons to avoid unwanted consequences.
access from whenever you like
Example: (from the C#Indepth link, second version, having simple thread safety, take note who the author of the article is!)
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
BEWARE always take thread safety into count!
As I got a response from #JonSkeet (yikes!), I think I have to explain the rationale behind my answer:
Pros:
It is better than having some non-standard way of doing so
It is better than having to pass it around to every bit of code that exists
Cons:
It is absolutely not recommended, if this requirement can be circumvented by any means
having a singleton map around is a serious bad smell: keeps references throughout the life of the application, leading to massive leaks more often than not
multithreaded behaviour is something that is not trivial, and especially difficult to go after if something misbehaves only very rarely (hidden race conditions, and whatever else lurking under the bed of a programmer during nightmares)
Also recommended reading:
Singleton pattern Wiki
MSDN: Implementing Singleton in C#
Clarification of the article on C#Indepth on Stack overflow - by the author himself
This is definitely a bit of a noob question, but my searches so afar haven't cleared the issue up for me.
A want a particular console app to store several class-level variables. In one case, I want to store a copy of my logging object, which I'll use in various places within the class. In another case, I want to store a simple type, a int value actually, which is only going to be used internally (doesn't need to be a property).
It appears that unless I specify these variables as static, I can't use them in Main() and beyond.
My understanding of static objects is that their values are shared across all instances of an object. Under normal operation, I'd expect their to be only one instance of my app, so this issue isn't a problem - but it has highlighted a lack of understanding on my part of something that is fairly fundamental.
In the case, of my logging object, I could see a case for making it static - sharing a log across multiple instances might be a benefit. However, it might not be the case... In the case of my int, I'd certainly never want this to be shared across instances.
So...
Am I misunderstanding the theory behind this?
Is there a different way I should be declaring and using my class-level variables?
Should I be avoiding using them? I could simply pass values as parameters from function to function, though it seems little a lot for work for no apparent gain.
EDIT: OK, the message is clear - my understanding of statics was largely correct, but the problem was one of structure and approach. Thanks for your replies.
Just encapsulate your application in another class, which you create and execute on the Main method:
class MyApp {
private MyLog lol = new MyLog();
private int myInt = 0;
public void Execute() {
// ...
}
}
class Program {
public static void Main() {
new MyApp().Execute();
}
}
You can still make the log field static if you want.
You should be creating a class outside of your Main function, and then creating an instance of that class from within Main.
EG
class MyConsoleApp
{
public static void Main()
{
MyClass mc = new MyClass();
}
}
Class MyClass
{
private MyLog lol as new MyLog();
private int myInt = 0;
}
The issue here is more or less purely syntactical: Because a static method can only access static fields, and the Main() method has to be static, this requires the used variables to be static. You never create an instance of the MyConsoleApp class.
Not really much theory here, only pragmatic requirements...
Thomas
I've got a class that manages a shared resource. Now, since access to the resource depends on many parameters, this class is instantiated and disposed several times during the normal execution of the program.
The shared resource does not support concurrency, so some kind of locking is needed. The first thing that came into my mind is having a static instance in the class, and acquire locks on it, like this:
// This thing is static!
static readonly object MyLock = new object();
// This thing is NOT static!
MyResource _resource = ...;
public DoSomeWork() {
lock(MyLock) {
_resource.Access();
}
}
Does that make sense, or would you use another approach?
Yes you can use a static variable to protect a shared resource.
You could also use typeof(class) as the expression inside lock. See the warning below though, with the static variable it is at least more protected to within your class.
I've got a class that is instantiated within any number of threads that are spooled up as needed. This means that any number of instantiated versions of this class can be used at any one time, and there's a portion of this class that needs to be locked to prevent concurrent access.
To prevent data issues between the various threads, I needed a way to lock a section of code from the other instantiated versions of the class in other threads. Since there can be multiple instantiated versions of this class running around, I can't just use a private member variable to lock (and I know not to use the Type, or anything publicly accessible); so I used a private static member variable.
Is that a reasonable approach to this problem? Or is there a better solution?
Sample code below:
public class MyClass
{
private static object LockingVar = new object();
public void MyPublicMethod()
{
lock (LockingVar)
{
// Do some critical code
}
}
EDIT
MyPublicMethod is making calls to a local SQLExpress instance, it can perform selects in addition to updates and inserts, so it needs to finish before another thread gets in there and mucks it up.
Looks fine to me. I'd also mark the LockingVar as readonly.
Yes, with your sample code, you'll achieve a global critical section on the method for all instances of the class.
If that's what you're looking for (and you have to ask yourself if you really want to have only ever one thread running that method at a time), you can also use the [MethodImpl(MethodImplOptions.Synchronized)] which gets you basically the same feature.
[MethodImpl(MethodImplOptions.Synchronized)]
public static void MyPublicMethod()
{
// Do some critical code
}
Note: this amounts to write lock(this){} if it's a instance method or lock(typeof(MyClass)) if it's a class (static) method. Both are frown upon, so your lock(obj) pattern is better.
From MSDN:
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Therefore your implementation seems to be right.