I have several objects inheriting from ClassA, which has an abstract method MethodA.
Each of these inheriting objects can allow up to a specific number of threads simutaneously into their MethodA.
The catch: Threads can only be in an object's MethodA, while no other objects' MethodA is being processed at the same time.
How can I solve this? I am thinking about using a semaphore, but don't know exactly how to do it, because I just can't wrap my head around the problem enough to get a solution.
EDIT:
Example code (may contain syntax errors:)
public class ClassA
{
public virtual void MethodA{}
}
public class OneOfMySubclassesOfClassA // there can be multiple instances of each subclass!
{
public override void MethodA{
// WHILE any number of threads are in here, THIS MethodA shall be the ONLY MethodA in the entire program to contain threads
EDIT2: // I mean: ...ONLY MethodA of a subclass (not of a instance of a subclass) in the entire program...
}
}
...and more subclasses...
The derived type is used as type argument in the base class together with a static semaphore to get one semaphore shared between all instances of each subclass. And then there is some mess to ensure that only one type is active. A quick test indicates that this works correctly but there is an issue.
Assume for example that the method of ClassA1 is currently executing. If new request to execute this methods arrive with high frequency it may happen that other derived classes get no chance to execute because there are constantly new threads executing the method of class ClassA1.
internal abstract class ClassA<TDerived> : ClassA
{
private const Int32 MaximumNumberConcurrentThreads = 3;
private static readonly Semaphore semaphore = new Semaphore(ClassA<TDerived>.MaximumNumberConcurrentThreads, ClassA<TDerived>.MaximumNumberConcurrentThreads);
internal void MethodA()
{
lock (ClassA.setCurrentlyExcutingTypeLock)
{
while (!((ClassA.currentlyExcutingType == null) || (ClassA.currentlyExcutingType == typeof(TDerived))))
{
Monitor.Wait(ClassA.setCurrentlyExcutingTypeLock);
}
if (ClassA.currentlyExcutingType == null)
{
ClassA.currentlyExcutingType = typeof(TDerived);
}
ClassA.numberCurrentlyPossiblyExecutingThreads++;
Monitor.PulseAll(ClassA.setCurrentlyExcutingTypeLock);
}
try
{
ClassA<TDerived>.semaphore.WaitOne();
this.MethodACore();
}
finally
{
ClassA<TDerived>.semaphore.Release();
}
lock (ClassA.setCurrentlyExcutingTypeLock)
{
ClassA.numberCurrentlyPossiblyExecutingThreads--;
if (ClassA.numberCurrentlyPossiblyExecutingThreads == 0)
{
ClassA.currentlyExcutingType = null;
Monitor.Pulse(ClassA.setCurrentlyExcutingTypeLock);
}
}
}
protected abstract void MethodACore();
}
Note that a wrapper method is used to call the actual implementation in MethodACore. All the synchronization objects shared between all derived classes are in a non-generic base class.
internal abstract class ClassA
{
protected static Type currentlyExcutingType = null;
protected static readonly Object setCurrentlyExcutingTypeLock = new Object();
protected static Int32 numberCurrentlyPossiblyExecutingThreads = 0;
}
The derived classes will look like this.
internal sealed class ClassA1 : ClassA<ClassA1>
{
protected override void MethodACore()
{
// Do work here.
}
}
internal sealed class ClassA2 : ClassA<ClassA2>
{
protected override void MethodACore()
{
// Do work here.
}
}
Unfortunately I have no time to explain how and why this works in more detail right now but I will update the answer tomorrow.
public abstract class Foo
{
private static Type lockedType = null;
private static object key = new object();
private static ManualResetEvent signal = new ManualResetEvent(false);
private static int threadsInMethodA = 0;
private static Semaphore semaphore = new Semaphore(5, 5);//TODO set appropriate number of instances
public void MethodA()
{
lock (key)
{
while (lockedType != this.GetType())
{
if (lockedType == null)
{
lockedType = this.GetType();
//there may be other threads trying to get into the instance we just locked in
signal.Set();
}
else if (lockedType != this.GetType())
{
signal.WaitOne();
}
}
Interlocked.Increment(ref threadsInMethodA);
}
semaphore.WaitOne();
try
{
MethodAImplementation();
}
finally
{
lock (key)
{
semaphore.Release();
int threads = Interlocked.Decrement(ref threadsInMethodA);
if (threads == 0)
{
lockedType = null;
signal.Reset();
}
}
}
}
protected abstract void MethodAImplementation();
}
So there are a few key points here. First off, we have a static object that represents the only instance that is allowed to have threads. null means the next thread to come along can put in "their" instance. If another instance is the "active" one the current thread waits on the manual reset event until either there is no locked instance, or the locked instance changed to what might possibly be that thread's instance.
It's also important to count the number of threads in the method to know when to set the locked instance to null (setting to to null without keeping track of that would let new instances start while a few of the previous instances were finishing.
Locks around another key at the start and end are rather important.
Also beware that with this setup it's possible for one type to starve out other types, so if this is a heavily contended resource it's something to watch out for.
Assuming you have a list of all relevant instances, this code will lock on all other instances and thus allow only one instance's code to be executed at any given time:
void MethodA()
{
foreach (var obj in objects)
if (obj != this)
Monitor.Enter(obj);
try
{
// do stuff
}
finally
{
foreach( var obj in objects)
if (obj != this)
Monitor.Exit(obj);
}
}
Related
The following code block, performs loading of an object in C#.
public bool IsModelLoaded { get; set; }
public override MyObject Load()
{
if (!IsModelLoaded)
{
Model = MyService.LoadMyObject(Model);
IsModelLoaded = true;
}
return Model;
}
My intention is to run this block only once, and hence loading the Model only once. Nevertheless, this code block runs twice from 2 different threads.
How can I make sure that this block runs only once? (on multiple threads).
Use the Lazy<T> Class:
private readonly Lazy<MyObject> myObject;
public MyClass()
{
myObject = new Lazy<MyObject>(() =>
{
return MyService.LoadMyObject();
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool IsModelLoaded
{
get { return myObject.IsValueCreated; }
}
public override MyObject Load()
{
return myObject.Value;
}
Simplest would be to add
[MethodImpl(MethodImplOptions.Synchronized)]
public override MyObject Load()
{
//snip
}
but be aware this puts a lock on the entire object, not just the method. Not really great practice.
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx
Synchronized
Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, whereas instance methods lock on the instance. Only one thread can execute in any of the instance functions, and only one thread can execute in any of a class's static functions.
I are trying to implement singleton pattern. But your version is not thread safe. Read more here: http://www.dofactory.com/Patterns/PatternSingleton.aspx. Try to use this implementation:
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
If you want to write thread safe code and make sure that the block runs only once, you can write like this:
private System.Object lockThis = new System.Object();
public override MyObject Load()
{
lock (lockThis) {
if (!IsModelLoaded)
{
Model = MyService.LoadMyObject(Model);
IsModelLoaded = true;
}
}
return Model;
}
Action myCodeBlock = ()=>
{
//do your job
//...
myCodeBlock = ()=>{};
}
After calling myCodeBlock() once it will be rewritten by method that does nothing. You still need to make sure this metod is called safely - use lock or whatever.
You can use lock Statement (C# Reference)
Create a static object (like a boolean) that determines if the code has ran or not by putting it in an if statement :)
EDIT: I'm not sure if this is threadsafe, so it might not be the solution for you.
At the moment I have the following class.
class BaseClass : IDisposable
{
private static List<BaseClass> instances = new List<BaseClass>();
protected BaseClass()
{
instances.Add(this);
}
~BaseClass()
{
Dispose();
}
public void Dispose()
{
instances.Remove(this);
}
}
So the lifetime of every class that inherit the BaseClass is infinitely until I close the program or I will call Dispose explicity.
Can I prevent this behaviour, so that lifetime is back to normal? (of course without removing the possibility to access the derived objects, otherwise my question make no sense)
I add the static List, to handle various actions to all classes that inherit BaseClass.
Edit
class DerivedClass : BaseClass
{
}
//This case works
using (DerivedClass _dc = new DerivedClass())
{
//Do something with object
}
//This object will live forever, because it is internally in the static list
//That behaviour is not desired
DerivedClass dc = new DerivedClass();
How I can get the bahaviour that DerivedClass dc calls his destructor after the normal lifetime (as it would not be in the list)?
Background
I want to fill the Properties of the derived classes with values from a config file and do it in base class. But if the config file changed, I have to change all properties of alll derived classes. So if you know a way to get all objects that implements the base class and needs to be changed, let me know it.
Update
Solution 1: Based on my question
With help from Steve Mitcham (Go to post) I found out how I can make a weak reference with few lines of code:
class BaseClass : IDisposable
{
private static List<GCHandle> handles = new List<GCHandle>();
protected BaseClass()
{
this.handle = GCHandle.Alloc(this, GCHandleType.Weak);
handles.Add(this.handle);
}
~BaseClass()
{
Dispose();
}
public void Dispose()
{
if (handle.IsAllocated)
{
//Do Something more to Dispose the Object
//...
handle.Free();
handles.Remove(handle);
}
}
public void DoSomethingWithTheList()
{
foreach (GCHandle handle in handles)
{
BaseClass bc = (BaseClass)handle.Target;
//Do something
}
}
}
Now If I call GC.Collect(); it will collect my unused derived classes (so I think the garbage collector will collect my objects normally as well) because the object itself has no reference in a list.
Thank you!
Solution 2: Subsrciber / Broadcaster Pattern
With this pattern it is simple too. Additionally the derived class can get the info if the values are changed.
Thank you Alireza (Goto post) and Thangadurai.
class ConfigurationBroadcaster
{
string path = "";
public string Path
{
get { return path; }
set
{
bool changed = path != value;
path = value;
if(changed)
if (ChangedConfigurationValues != null)
{
Delegate[] invocationList = ChangedConfigurationValues.GetInvocationList();
foreach (var item in invocationList)
{
Type t = item.Target.GetType();
PropertyInfo[] pInfos = t.GetProperties();
foreach (PropertyInfo pInfo in pInfos)
{
//new object() have to be the value from config file
//5 is used to set Width and Height from BroadcastSubscriber for this example
pInfo.SetValue(item.Target, 5/* new object()*/, null);
}
}
ChangedConfigurationValues(this, new EventArgs());
}
}
}
public event EventHandler ChangedConfigurationValues;
}
class BaseBroadcastSubscriber
{
ConfigurationBroadcaster broadcaster;
protected BaseBroadcastSubscriber(ConfigurationBroadcaster broadcaster)
{
this.broadcaster = broadcaster;
this.broadcaster.ChangedConfigurationValues += new EventHandler(broadcaster_ChangedConfigurationValues);
}
void broadcaster_ChangedConfigurationValues(object sender, EventArgs e)
{
Console.WriteLine("Configuration values changed");
}
}
class BroadcastSubscriber : BaseBroadcastSubscriber
{
int width,height;
public int Width
{
get { return width; }
set { width = value; }
}
public int Height
{
get { return height; }
set { height = value; }
}
public BroadcastSubscriber(ConfigurationBroadcaster broadcaster)
: base(broadcaster)
{
}
}
Without seeing more of your program it would be difficult to determine whether your approach could be improved. However, without fundamentally changing your design I would use WeakReferences to track your objects. The UpdateClasses method is to simulate your reconfigure action.
class BaseClass : IDisposable
{
private WeakReference<BaseClass> myReference;
private static List<WeakReference<BaseClass>> instances = new List<WeakReference>();
public static UpdateClasses(MyData stuff)
{
foreach(var ref in instances)
{
BaseClass target;
if (ref.TryGetTarget(out target))
{
// code to update target here
}
}
}
protected BaseClass()
{
myReference = new WeakReference<BaseClass>(this,true);
instances.Add(myReference);
}
~BaseClass()
{
Dispose();
}
public void Dispose()
{
instances.Remove(myReference);
}
}
The weak references will not keep your objects alive. When they get garbage collected they will remove their references from the instance list. Note, however, that this implementation will cause your objects to stay alive in the garbage collector longer than normal due to the requirement for the finalizer, and this may decrease the performance of the application over time.
Despite Steve Mitchman's answer, you could design a broadcaster class providing an event which gets fired whenever a change in config file is detected. Derived classes (objects) could subscribe to this event and unsubscribe upon being get GC collected or finalized. This approach follows open/closed principle very well.
When your BaseClass instance is off, that is both when you call the Dispose and when the instance itself is destroyed. These cases are normal.
I am trying to restrict access to an singletone object so only one thread
use it at time, Furthermore, I want to prevent from the same thread accessing twice
to the restricted code.
I tried the Lock method and i found out that its dosn't lock the thread that locked her, but only other threads..
as below:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
public class SomeWorker
{
private readonly Timer _doWorkTimer = new Timer(20);
public SomeWorker()
{
InitiateTimer();
}
private void InitiateTimer()
{
_doWorkTimer .Elapsed += DoWorkElapse;
_doWorkTimer .Enabled = true;
}
private void DoWorkElapse(object source, ElapsedEventArgs e)
{
DoSomeWork();
}
private void DoSomeWork()
{
// I know that lock on string is wrong!
// Its just for the example only I
// Its just to make sure all the program is use the same lock..
lock ("ConnectionLock")
{
Console.WriteLine("Lock");
var inst = Singletone.Instance;
// Do Some Work on "inst" ...
Console.WriteLine("Unlock");
}
}
}
The result in the console for example is:
.
.
.
Lock
Unlock
Lock
Lock
Unlock
.
.
.
As we can see, 2 Lock comments shows one after another
So its mean that the "DoSomeWork()" accessed twice by the timer thread.
Anyone have any idea how to make this lock work?
Other Sync methods maby?
thanx.
You aren't doing your locking properly (and to top it off you are taking a lock on a string which is a big no-no). To save time, please read this article from Jon Skeet and implement one of the patterns to save yourself a headache.
In your code you have
public static Singletone Instance()
{
if (_instance == null)
{
lock (_instance)
{
if (_instance == null)
{
_instance = new Singletone ();
}
}
}
return _instance;;
}
Think about it. if (_instance == null) you do lock (_instance). So you lock using null. That's not good at all.
In MSDN lock Statement (C# Reference) the given example of how to use lock is:
class Account
{
decimal balance;
private Object thisLock = new Object();
public void Withdraw(decimal amount)
{
lock (thisLock)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}
I guess you should follow it and have a separate object to use it as a lock.
And secondly, thread syncronization primitives are used to separate access to shared resources for different threads. If you need to separate access from one thread, you simply need to use flags. Something like this:
bool isBusy = false;
public static void Foo()
{
if (!isBusy)
{
isBusy = true;
try
{
//do the job
}
finally
{
isBusy = false;
}
}
}
Here you should understand that you simply skip the "locked-by-flag" code. On the contrary if you want to make the thread wait for itself, especially in a multithreading application, I guess it looks like it should be redesigned.
The easiest way to implement a singleton in .NET is:
public class Singleton : IDisposable
{
private readonly static Singleton _instance = new Singleton();
private readonly static object lockObject = new object();
static Singleton()
{
}
private Singleton()
{
InitiateConnection();
}
public static Singleton Instance
{
get { return _instance; }
}
/// <summary>
/// Method that accesses the DB.
/// </summary>
public void DoWork()
{
lock (lockObject)
{
//Do Db work here. Only one thread can execute these commands at a time.
}
}
~Singleton()
{
//Close the connection to DB.
//You don't want to make your singleton class implement IDisposable because
//you don't want to allow a call to Singleton.Instance.Dispose().
}
}
Read the excellent article on Singleton Pattern implementations in .NET that Bryan suggested in his answer. The above implementation is based on the fourth version described in the article. The CLR guarantees that the construction of the static field will thread-safe hence you do not need locking there. However you will need locking if your object has state (fields) that can be changed.
Note that there is a private readonly object used for ensuring mutual exclusion on the DoWork method. This way a single thread can call DoWork at a time. Also note that there is no way that the same thread can call this method twice at the same time since a thread executes instructions sequentially. The only way this method could be called twice from a single thread is if inside DoWork you call another method that eventually calls DoWork. I can't see the point of doing this and if you do then take care to avoid stack overflows. You could follow the suggestion of Konstantin and use a flag but IMHO you should redesign DoWork to do just one thing and avoid scenarios like these.
The following code block, performs loading of an object in C#.
public bool IsModelLoaded { get; set; }
public override MyObject Load()
{
if (!IsModelLoaded)
{
Model = MyService.LoadMyObject(Model);
IsModelLoaded = true;
}
return Model;
}
My intention is to run this block only once, and hence loading the Model only once. Nevertheless, this code block runs twice from 2 different threads.
How can I make sure that this block runs only once? (on multiple threads).
Use the Lazy<T> Class:
private readonly Lazy<MyObject> myObject;
public MyClass()
{
myObject = new Lazy<MyObject>(() =>
{
return MyService.LoadMyObject();
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool IsModelLoaded
{
get { return myObject.IsValueCreated; }
}
public override MyObject Load()
{
return myObject.Value;
}
Simplest would be to add
[MethodImpl(MethodImplOptions.Synchronized)]
public override MyObject Load()
{
//snip
}
but be aware this puts a lock on the entire object, not just the method. Not really great practice.
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx
Synchronized
Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, whereas instance methods lock on the instance. Only one thread can execute in any of the instance functions, and only one thread can execute in any of a class's static functions.
I are trying to implement singleton pattern. But your version is not thread safe. Read more here: http://www.dofactory.com/Patterns/PatternSingleton.aspx. Try to use this implementation:
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
If you want to write thread safe code and make sure that the block runs only once, you can write like this:
private System.Object lockThis = new System.Object();
public override MyObject Load()
{
lock (lockThis) {
if (!IsModelLoaded)
{
Model = MyService.LoadMyObject(Model);
IsModelLoaded = true;
}
}
return Model;
}
Action myCodeBlock = ()=>
{
//do your job
//...
myCodeBlock = ()=>{};
}
After calling myCodeBlock() once it will be rewritten by method that does nothing. You still need to make sure this metod is called safely - use lock or whatever.
You can use lock Statement (C# Reference)
Create a static object (like a boolean) that determines if the code has ran or not by putting it in an if statement :)
EDIT: I'm not sure if this is threadsafe, so it might not be the solution for you.
I am using .net 1.1. I have a session class in which I have stored many static variables that hold some data to be used by many classes.
I want to find a simple way of destroying this class instead of resetting every variable one by one. For example if there is a static class MyStatic, I would have liked to destroy/remove this class from the memory by writing MyStatic = null, which is not currently possible,
Additional question.
The idea of singleton is good, but I have the following questions:
If singleton is implemented, the 'single' object will still remain in the memory. In singleton, we are only checking if an instance is already existing. how can i make sure that this instance variable also gets destroyed.
I have a main class which initializes the variable in the static class. Even if I plan to implement a Rest() method, I need to call it from a method, for eg, the destructor in the main class. But this destructor gets called only when GC collects this main class object in the memory, which means the Reset() gets called very late
thanks
pradeep
Don't use a static class to store your variables. Use an instance (and make it a singleton if you only want one instance at any given time.) You can then implement IDisposible, and just call Dispose() when you want to destroy it.
For more information check out this site: http://csharpindepth.com/Articles/General/Singleton.aspx
EDIT
The object is still subject to garbage collection, so unless you are using lots of unmanaged resources, you should be fine. You can implement IDisposible to clean up any resources that need to be cleaned up as well.
Instead of a static class, have a static instance of a class:
class Foo
{
public int Something;
public static Foo Instance = new Foo();
public void Reset()
{
Instance = new Foo();
}
}
void test
{
int i = Foo.Instance.Something;
}
You can also delegate to an instance of the class:
class Foo
{
public int Something
{
get { return instance.something; }
}
private int something;
private static Foo instance = new Foo();
public void Reset()
{
instance = new Foo();
}
}
void test
{
int i = Foo.Something;
}
There's no way to destroy a static unless it resides in a separate AppDomain in which case you can get rid of it by unloading the AppDomain. However it is usually better to avoid statics.
EDIT: Additional question
When the singleton is no longer referenced it will be collected just as everything else. In other words, if you want it collected you must make sure that there are no references to it. It goes without saying that if you store a static reference to your singleton, you will have the same problem as before.
Use a Singleton like ktrauberman said, and have an initialization method or a reset method. You only have to write the code once and call the method.
You destroy objects, not classes. There's nothing wrong with static classes--C# provides them for a reason. Singletons are just extra overhead, unless you actually need an object, e.g. when you have to pass the object as a parameter.
Static classes contain only static variables. These variables tend to last for the lifetime of the app, in which case you don't have to worry about disposing referenced objects, unless you have a mild case of OCD. That just leaves the case where your static class allocates and releases resources throughout its lifetime. Dispose of these objects in due course as you usually would (e.g., "using...").
The best way in your condition is to have an Reset() method built-in as well, which can reset the values of the class.
class myclass
{
private static myclass singleobj = null;
private myclass(){}
public static myclass CreateInstance()
{
if(singleobj == null)
singleobj = new myclass();
return singleobj
}
}
Building on Ahemd Said's answer: (and props to him!)
class Singleton
{
private static Singleton instance = null;
private Singleton(){} // private constructor: stops others from using
public static Singleton Instance
{
get { return instance ?? (instance = new Singleton()); }
set {
if (null != value)
{ throw new InvalidValueException(); }
else
{ instance = null; }
}
}
}
void SampleUsage()
{
Singleton myObj = Singleton.Instance;
// use myObj for your work...
myObj.Instance = null; // The set-operator makes it ready for GC
}
(untested... but mostly right, I think)
You could also add in usage of the IDispose interface for more cleanup.
You can create a method in the static class which resets the values of all properties.
Consider you have a static class
public static class ClassA
{
public static int id=0;
public static string name="";
public static void ResetValues()
{
// Here you want to reset to the old initialized value
id=0;
name="";
}
}
Now you can use any of the below approaches from any other class to reset value of a static class
Approach 1 - Calling directly
ClassA.ResetValues();
Approach 2 - Invoking method dynamically from a known namespace and known class
Type t1 = Type.GetType("Namespace1.ClassA");
MethodInfo methodInfo1 = t1.GetMethod("ResetValues");
if (methodInfo1 != null)
{
object result = null;
result = methodInfo1.Invoke(null, null);
}
Approach 3 - Invoking method dynamically from an assembly/set of assemblies
foreach (var Ass in AppDomain.CurrentDomain.GetAssemblies())
{
// Use the above "If" condition if you want to filter from only one Dll
if (Ass.ManifestModule.FullyQualifiedName.EndsWith("YourDll.dll"))
{
List<Type> lstClasses = Ass.GetTypes().Where(t => t.IsClass && t.IsSealed && t.IsAbstract).ToList();
foreach (Type type in lstClasses)
{
MethodInfo methodInfo = type.GetMethod("ResetValues");
if (methodInfo != null)
{
object result = null;
result = methodInfo.Invoke(null, null);
}
}
break;
}
}
Inject the objects into the static class at startup from a non static class that implements IDisposable, then when your non static class is destroyed so are the objects the static class uses.
Make sure to implement something like "Disable()" so the static class is made aware it's objects have just been set to null.
Eg I have a logger class as follows:
public static class Logger
{
private static Action<string, Exception, bool> _logError;
public static void InitLogger(Action<string, Exception, bool> logError)
{
if(logError != null) _logError = logError;
}
public static void LogError(string msg, Exception e = null, bool sendEmailReport = false)
{
_logError?.Invoke(msg, e, sendEmailReport);
}
In my constructor of my Form I call the following to setup the logger.
Logger.InitLogger(LogError);
Then from any class in my project I can do the following:
Logger.LogError("error",new Exception("error), true);