[Solved] Function should get called only once


Memoise it. It’ll still be called multiple times, but only do the full work once:

private List<string> _states; //if GetStateList() doesn't depend on object
                              //state, then this can be static.
public List GetStateList()
{
   if(_states == null)
   {
     List lstState=new List();
     lstState.add("State1");
     lstState.add("State2");
     lstState.add("State3");
     _states = lstState;
   }
   return _states;
}

Depending on threading issues, you may wish to either:

  1. Lock on the whole thing. Guaranteed single execution.
  2. Lock on the assignment to _states. There may be some needless work in the early period, but all callers will receive the same object.
  3. Allow for early callers to overwrite each other.

While the last may seem the most wasteful, it can be the best in the long run, as after the initial period where different calls may needlessly overwrite each other, it becomes a simpler and faster from that point on. It really depends on just how much work is done, and how often it may be concurrently called prior to _states being assigned to.

1

solved Function should get called only once