有没有办法防止事件处理程序自身触发? [英] Is there a way to prevent an event handler from firing over itself?

查看:101
本文介绍了有没有办法防止事件处理程序自身触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以快速连续发生的事件的事件处理程序。在某些情况下,当事件再次触发(毫秒)时,处理程序仍然会执行。



有没有办法使这些处理程序...串行?那么事件调用#2才能在事件调用#1完成之前启动?



如果这是一个糟糕的想法,为什么?这是一个在后台运行无人值守的批处理过程,所以我并不非常担心一个调用阻止另一个调用可能发生的性能问题。

解决方案

使用多线程控件锁定。这样可以防止您的代码在同一时刻一次运行。



EDITED

示例: p>

  public class Foo 
{
private static object _lockKey = new object();

private void YourEventHandlerMethod(object sender,EventArgs e)
{
lock(_lockKey)
{
//您放在此块内的代码将一次只能执行
//一次。

//如果第二次调用有意在
//结束第一次调用之前使用此块,则第二次调用(线程)
//将搁置
}
}
}


I have an event handler for an event that can occur in rapid succession. In some cases, the handler will still be executing when the event fires again (within milliseconds).

Is there anyway to make these handlers...serial? So, Event Invocation #2 cannot start until Event Invocation #1 has completed?

If this is an awful idea, why? This is a batch process that runs unattended in the background, so I'm not terribly concerned about performance issues that might occur from one invocation blocking another.

解决方案

Use the mult-thread controle lock. This prevents that your code will be run more the one time in same moment.

EDITED
EXAMPLE:

public class Foo
{
    private static object _lockKey = new object();

    private void YourEventHandlerMethod(object sender, EventArgs e)
    {   
        lock (_lockKey)
        {
            // the code you put inside this block will be execute only
            // once at time.

            // If a second call has the intention to use this block before
            // the conclusion of the first call, the second call (the thread)
            // will be put in hold.
        }
    }
}

这篇关于有没有办法防止事件处理程序自身触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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