Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make some lines of code to run only one time

Tags:

c#

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();
....
//...
}
like image 698
Bohn Avatar asked Nov 29 '22 09:11

Bohn


1 Answers

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;
        }
    }
}
like image 122
Douglas Avatar answered Dec 16 '22 23:12

Douglas