Click here to Skip to main content
15,894,410 members

Response to: Run method one time only

Revision 1
Here is one way to only run a method in code once. As you can see it uses a bool flag and a for loop to simulate multiple times being ran. After the first time the OnlyOnce method executes it sets the flag to true signifying its been ran and will not run within that for loop anymore.

C#
public class TestClass
{
    private bool HasAlreadyRan = false;

    public TestClass()
    {
        RunMethod();
    }

    public void RunMethod()
    {
        for(int i = 0; i < 10; i++)
        {
            if(!HasAlreadyRan)
            {
                OnlyOnce
            }
        }
    }

    public void OnlyOnce()
    {
        //Run Code Here

        HasAlreadyRan = true;
    }
}
Posted 18-Jan-13 12:50pm by David_Wimbley.
Tags: