since you said you want restrict the execution only once for a event trigger, I would like to know the real problem so that we can suggest a better solution. I suspect you are trying to find a workaround for your problem by restricting the execution. was it true?

Solution 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.

Solution 3

A problem with the flag method is that some code could clear your flag (via Reflection if necessary) and run the method again. To make it a little more secure you could put the special method in separate class.

I haven't read all of Sergey's article, but it is probably pretty good.

Fascinating, PIEBALDconsult, I have made frequent use of static constructors: I like them. And, even though some OOP "purists" seem to have a real gut-level antipathy against "static classes:" I like those, too :)

Your point about the possibility of some code changing a boolean flag, used to insure single execution of a method, via reflection is very thought-evoking, even if it's hard for me to imagine a scenario in which this could actually happen.

Also interesting that VB.NET has this method-scoped static variable capacity: although I'll never touch that, since I'll never touch VB.NET again. Nothing against VB.NET, personally, however, just that I find everything in C# I need :)

Solution 2

You can do it in a very simple way, but do it over, again and again. Or, you can do it in a very universal way.

Nearly everyone knows the simple way, but, to best of my knowledge, the universal way is happened to be only mine. It's is very exotic but fully legitimate and reliable, as it is totally based on standard .NET library (that is, BCL). I discuss both in my article. Please see:Wish You Were Here… Only Once[^].