Two classes in the same assembly: Class A
and Static
Class B
In a method of ClassA
, I am calling a method in ClassB
,... but I want that to be called only one time and not every single time that I am caling that method of ClassA
...
currently I am setting a global property -Ran - to see if that method has been ran before or not...well it works but I feel that this is not the best design. I was wondering if there are better ways to do the same?
Thanks.
ClassA.MyMethod(...)
{
....
//....
if (ClassB.Ran != 1)
ClassB.Foo();
....
//...
}
You need to be careful on how strictly the “only one time” restriction is to be interpreted. Static methods are generally assumed to be thread-safe; if you really want to ensure that your method is only run once, even in the case of racing threads, then you need to use a synchronization mechanism, the simplest example being a lock
:
private static bool isRun = false;
private static readonly object syncLock = new object();
public void MyMethod()
{
lock (syncLock)
{
if (!isRun)
{
Foo();
isRun = true;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With