仅运行一次方法 [英] Run method one time only

查看:77
本文介绍了仅运行一次方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我怎么能在代码开头只使用一次方法,知道这个方法是一个总是运行的事件的一部分

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 always

Application.Idle += Myevent;





提前致谢,

z3ngew



Thanks in advance,
z3ngew

推荐答案

您可以在执行时删除事件处理程序。实际上,您手动添加的任何事件处理程序通常也应手动删除(在某些时候)。

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 execute the code 
    // again if an exception is thrown)...
}



能够删除处理程序的唯一必要条件是它是一个实际的函数而不是lambda表达式。


The only thing that is necessary to be able to remove an handler is that it is an actual function and not a lambda expression.


这是一种只在代码中运行一次方法的方法。正如您所看到的,它使用bool标志和for循环来模拟多次运行。在第一次执行OnlyOnce方法之后,它将标志设置为true表示已经运行,并且不再在for循环中运行。



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 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;
    }
}


取决于。你能把它变成一个静态构造函数吗?



flag方法的一个问题是某些代码可以清除你的标志(必要时通过Reflection)并再次运行该方法。为了使它更安全,你可以将特殊方法放在单独的类中。



我还没看过谢尔盖的所有文章,但它是可能还不错。



另一个想法是VB(但不是C#:()允许你定义一个方法范围的(静态)变量,它可以工作。 br />
http://msdn.microsoft.com/ en-us / library / z2cty7t8(v = vs.110).aspx [ ^ ]
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 Sergey''s article, but it is probably pretty good.

Another thought is that VB (but not C# :( ) allows you to define a method-scoped (static) variable, which could work.
http://msdn.microsoft.com/en-us/library/z2cty7t8(v=vs.110).aspx[^]


这篇关于仅运行一次方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆