Click here to Skip to main content
15,891,745 members
Articles / Programming Languages / C#

Run method one time only

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
18 Jan 2013CPOL 0  
You can remove the event handler when it is executed. In fact, any event handler that you add manually should typically also be removed manually (at some point).void Myevent(object sender, EventArgs e){ Application.Idle -= Myevent; // Other code here (assuming you don't want to...

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
18 Jan 2013z3ngew 4 alternatives  
Hello everyone,How can i use a method only one time at the beginning of the code, knowing that this method is part of an event that runs alwaysApplication.Idle += Myevent;Thanks in advance,z3ngew
Please Sign up or sign in to vote.
18 Jan 2013David_Wimbley
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.public...
Please Sign up or sign in to vote.
18 Jan 2013PIEBALDconsult
It depends. Can you make it a static constructor?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...
Please Sign up or sign in to vote.
18 Jan 2013Sergey Alexandrovich Kryukov
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...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
Programmer at Maid LABS from 2003 (www.maidlabs.com)

Programmer-Analyst at Viasat Geo Technoligies from 1995 to 2002 (www.viasat-geo.com).

I have studied at École Polytechnique de Montréal in computer engineering.

Comments and Discussions