加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通过附加/分离事件来控制事件触发频率.不好的做法?

发布时间:2020-12-15 17:20:31 所属栏目:百科 来源:网络整理
导读:昨天我提供了问题 How do you control event firing in C#?的答案,简而言之,问题如下: “There is an event that fires whenever a new frame is received from the camera. However,this happens more frequently than I’d like … How can I control whe
昨天我提供了问题 How do you control event firing in C#?的答案,简而言之,问题如下:

“There is an event that fires whenever a new frame is received from the camera. However,this happens more frequently than I’d like … How can I control when the event fires?”

在我的回答中,我提供了下面的代码,今天早上我发现我有2个downvotes没有任何评论.我担心的主要不是代表的丢失,而是我在各种应用程序中使用自己的逻辑,并且downvotes可能表明我的实现是糟糕的实践或不利于性能.因此,我问这个问题是为了澄清以这种方式附加/分离事件控制器是否有任何问题?

public MyObject()
{    
   MyTimer = new System.Timers.Timer(100); // 10 Hz
   MyTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
   MyTimer.Enabled = true;
}

private void ImageDataUpdated(object sender,EventArgs e) 
{
   // detach from the event to keep it from firing until the timer event has fired.
   MyImageObject.Update -= new UpdateEventHandler(ImageDataUpdated);

    // do stuff
}

private static void OnTimedEvent(object source,ElapsedEventArgs e)
{
    // (re-)attach to the event handler.
   MyImageObject.Update += new UpdateEventHandler(ImageDataUpdated); 
}

此外,我写了以下内容,指的是在实际准备要发送给订阅者的数据之前,可以检查您是否有任何订阅者.在某些情况下,这可能会导致CPU使用率降低.对我来说似乎是对的(我自己也这样做了),但这句话有什么不对吗?

Using this strategy there is a good chance that you are preventing the underlying image object from doing additional work while the event handler is detached (of course this depends on the implementation of the image object). Chances are that you are saving CPU-cycles for your own image processing.

解决方法

我想他们认为基于不相关的计时器动态添加和删除事件是一件坏事.虽然这是一个在某个地方可能有用的巧妙技巧,但总有一天,我倾向于同意它们.对其他对象的事件处理程序的外部控制并不表示良好的封装.

另一种方法是简单地检查在调用之间接收事件处理程序中是否已经过了足够的时间并决定是否处理.这与逻辑在实时游戏或类似应用程序中的工作方式更为一致,这意味着您不会经常从外部连接和断开事件处理程序.

实际事件调用本身的开销很小,所以不要担心每帧几次调用,只要每次都不执行“慢速部分”(即执行实际工作的位).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读