你如何控制事件在C#中射击? [英] How do you control event firing in C#?
问题描述
我写了一个程序,它通过一个网络摄像头提供的图像进行一些处理。有每当从摄像机接收到的新帧触发一个事件。然而,这种情况发生的频率比我想 - 非常频繁,前一个新的事件出现,并再次调用同样的功能我的图像处理功能没有完成。
I wrote a program that does some processing on an image delivered via a web cam. There is an event that fires whenever a new frame is received from the camera. However, this happens more frequently than I'd like - so frequently that my image processing function doesn't complete before a new event appears and calls the same function again.
我如何控制事件触发时?我可以执行我的图像处理,比如,每5事件呢?我相信我有这个伪代码想通了,但我宁愿看到在C#中的一些例子。
How can I control when the event fires? Can I execute my image processing, say, every 5 events instead? I believe I have the pseudo code figured out, but I would prefer to see some examples in C#.
推荐答案
将事件回调把守,如下所示。然后它不会在同一时间做处理多次
Place the event callback "guarded" as follows. Then it won't be doing the processing many times at the same time.
private bool m_active;
void YourCallback(object sender, EventArgs args)
{
if(!m_active)
{
try
{
m_active = true;
// Do the work here...
}
finally { m_active = false; }
}
}
编辑:线程,如果使用f.i.安全信号灯。
private System.Threading.Semaphore m_Semaphore = new System.Threading.Semaphore(0, 1);
void YourCallback(object sender, EventArgs args)
{
if(m_Semaphore.WaitOne(0))
{
try
{
// Do the work here...
}
finally { m_Semaphore.Release(); }
}
}
这篇关于你如何控制事件在C#中射击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!