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.
Related
I have a singleton defined like this:
public partial class MoonDataManager
{
static MoonDataManager _singletonInstance;
public static MoonDataManager SingletonInstance
{
get
{
return _singletonInstance;
}
private set
{
_singletonInstance = value;
}
}
I have a function that safely creates the instance:
public static async Task<MoonDataManager> CreateSingletonAsync()
{
_singletonInstance = new MoonDataManager();
Should I:
return _singletonInstance; (field)
or
return SingletonInstance; (property)
I'm concerned with Garbage Collection, especially in iOS or Android within Xamarin.
Also if there are naming patterns for this in C# let me know if I deviated from a standard.
Update:
Now I think I really got myself stuck with threading and async methods. Here are the objects and their goals:
MoonDataManager : Run the RegisterTable<Models.IssuerKey> once per table. This is a generic method that essentially runs (new MobileServiceSQLiteStore).DefineTable<T>()
OfflineStore : This is a MobileServiceSQLiteStore.
MobileClient : This is a MobileServiceClient.
MoonDataManager Dependencies: The MoonDataManager requires OfflineStore and MobileClient to finish initialization. Specifically, it does a MobileServiceClient.SyncContext.InitializeAsync(OfflineStore)
I'm not sure how to make sense of this spaghetti of dependencies... or how to make the code look nice, and be thread safe.
Here is the new iteration of the code:
private readonly Lazy<MobileServiceClient> lazyMobileClient =
new Lazy<MobileServiceClient>(() => new MobileServiceClient(Constants.ApplicationURL), true); // true for thread safety
public MobileServiceClient MobileClient { get { return lazyMobileClient.Value; } }
private readonly Lazy< MobileServiceSQLiteStore> offlineDB =
new Lazy<MobileServiceSQLiteStore>(() => new MobileServiceSQLiteStore(Constants.OfflineDBName), true ); // true for thread safety
private MobileServiceSQLiteStore OfflineStore { get { return offlineDB.Value; } }
private static readonly Lazy<MoonDataManager> lazy = new Lazy<MoonDataManager>(() => new MoonDataManager(), true); // true for thread safety
public static MoonDataManager Instance { get { return lazy.Value; } }
private MoonDataManager()
{
MoonDataManager.Instance.RegisterTable<Models.IssuerKey>();
// Initialize file sync
// todo: investigate FileSyncTriggerFactory overload.
//Was present on Mar 30, 2016 Channel9 https://channel9.msdn.com/events/Build/2016/P408
MoonDataManager.Instance.MobileClient.InitializeFileSyncContext
(new IssuerKeyFileSyncHandler(Instance), Instance.OfflineStore);
// NOTE THE ASYNC METHOD HERE (won't compile)
await MoonDataManager.Instance.MobileClient
.SyncContext.InitializeAsync(MoonDataManager.Instance.OfflineStore,
StoreTrackingOptions.NotifyLocalAndServerOperations);
}
For .NET 4 or higher, you can use the Lazy<T> and create it like this.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton(), true); // true for thread safety
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It will be created only if it is accessed and only the first time and it is threadsafe.
The definition
static MoonDataManager _singletonInstance;
ensures that the instance of MoonDataManager is a GC root, and it will not be collected until the application domain ends, because it is a static value.
I'd return the private singleton and forego the auto property that you have.
public partial class MoonDataManager
{
private static readonly Lazy<MoonDataManager> _manager =
new Lazy<MoonDataManager>(() => new MoonDataManager());
public static MoonDataManager SingletonInstance => _manager.Value;
}
When MoonDataManager.Value is accessed for the first time, it is initialized using the Func<MoonDataManager> that was passed to the constructor for Lazy<T>. On subsequent accesses, the same instance is returned.
A Singleton creates itself the first time it's accessed, in a way that ensures only one instance will get created, even if a second thread tries to access it while it's still being instantiated
your CreateSingletonAsync() violates this, and looks like it'd allow for multi-thread nastiness
You want something like:
public static MoonDataManager SingletonInstance
{
get
{
if (_singletonInsatnce != null)
return _singletonInstance;
lock (lockobject)
{
// check for null again, as new one may have been created while a thread was waiting on the lock
if (_singletonInsatnce != null)
return _singletonInstance;
else
// create new one here.
}
}
// no setter, because by definition no other class can instantiate the singleton
}
All this is just to ensure that two threads asking for one object don't end up creating two objects, or the second thread getting a half-created object if the first thread's one is still being created.
NB: Singletons have become unfashionable.
NB: If you can be sure that you've got time to create your object before it's ever accessed, you can just use a static member and create it on application start.
Your question "should I return the property or field" doesn't make sense -- you're already returning the field from the property getter, which is standard practise. Where else are you wanting to return something?
You should return the private instance. You can read more about the singleton pattern on MSDN. The standard singleton implementation is as follows:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Although, normally, you don't have a setter for the property. This pattern has already previously been discussed on SO.
I have a function which does "migration" from an old format to a new format. I need this to occur in the constructor of my object, but not the static constructor because an argument is needed. How can I have a piece of code only execute exactly one time?
For some context:
class Foo
{
public Foo(string bar)
{
ShouldOnlyExecuteOnce(bar);
}
}
and then usage could be (with each line a different thread)
var f = new Foo("bar");
var fb = new Foo("meh");
etc
How can I properly guard the "ShouldOnlyExecuteOnce" method?
Because this is a sort of "migration" type function, I want for the first object created to "win" and get to migrate the old data into this new object. Later objects that get constructed should not attempt to execute this function, even if their arguments are different
You could use double check locking.
class Foo
{
private static bool ShouldOnlyExecuteOnceExecuted = false;
private static readonly object Locker = new object();
public Foo(string bar)
{
SetShouldOnlyExecuteOnce(bar);
}
private void SetShouldOnlyExecuteOnce(string bar)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
lock(Locker)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
ShouldOnlyExecuteOnce(bar);
ShouldOnlyExecuteOnceExecuted = true;
}
}
}
}
}
I would generally recommend against implementing subtle mechanisms such as double-checked locking, especially when you already have them implemented in the BCL. In this case:
public class SafeInitializater
{
private bool _initialized;
private object _dummy;
private object _syncLock;
public void InitializeOnce(Action initializer)
{
LazyInitializer.EnsureInitialized(ref _dummy, ref _initialized, ref _syncLock,
() => {
initializer();
return null;
});
}
}
Usage sample:
var initializer = new SafeInitializater(); //or you could make this static somewhere
var t1 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
var t2 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
await Task.WhenAll(t1, t2);
You need a mutex. This is exactly the kind of usecase mutexes are designed for.
http://www.dotnetperls.com/mutex
you should read about monitors, semaphors and the sigelton design-pattern
What is the Mutex and semaphore In c#? where we need to implement?
http://www.c-sharpcorner.com/UploadFile/1d42da/threading-with-semaphore-in-C-Sharp/
I have no idea, but I'd guess/try:
1 - A static class acting as a wrapper and calls your method in the static constructor
2 - Some IoC container?
3 - Singleton?
4 - Lock?
5 - All of above?
I agree with P.Brian that this seems like a singleton pattern. You can see a very good article on it here http://csharpindepth.com/articles/general/singleton.aspx which breaks it down nicely. Generally the best solution is #4;
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
A Singleton pattern should work.
Parrotting Jon Skeet: http://csharpindepth.com/articles/general/singleton.aspx
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Singleton's are constructed one time. Although, the part about passing in a new string value could present an issue. Is this value ignored on all consecutive calls?
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);
}
}
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.