如何减少连续触发事件的事件处理频率



我正在学习c#中的任务和async/await。所以请考虑一下我这个问题的愚蠢。

类中存在一个事件DummyEvent。事件处理程序DummyEventHandler订阅了这个event,它处理大量的CPU绑定任务,实际上不需要如此频繁地使用。

因此,如果连续激发DummyEvent,我希望DummyEventHandler以降低的频率响应,或者在连续性结束时响应。

因此,我的想法是将大任务提取到一个单独的任务中,并使其在进行之前延迟500毫秒。延迟结束后,它将检查是否再次安排了相同的任务(连续事件激发),如果为true,则避免进行大计算。

以下是我对这个想法的天真实现:

int ReducedCall = 0;
int TotalCallActual = 0;
protected void DummyEventHandler(object sender, bool arg)
{
TotalCallActual++;
LargeCPUBoundTask(); // there is a green underline here, but I think it's ok, or.. is it?
}
async Task LargeCPUBoundTask()
{
ReducedCall = TotalCallActual;
await Task.Delay(500);
// if this task is called again in this time, TotalCallActual will increase
if (ReducedCall == TotalCallActual)
{
// do all the large tasks
……
ReducedCall = 0;
TotalCallActual = 0;
}
}

但问题是,我没有得到我想要的。Task.Delay(500)行实际上并没有等待,或者,如果它真的等待了,那就有问题了,因为我经历了蹒跚。

有什么更好的想法,或者有什么改进/纠正吗?

询问任何其他信息。

感谢

您可以利用反应式扩展来做到这一点:

void Main()
{
var generator = new EventGenerator();
var observable = Observable.FromEventPattern<EventHandler<bool>, bool>(
h => generator.MyEvent += h,
h => generator.MyEvent -= h);
observable
.Throttle(TimeSpan.FromSeconds(1))
.Subscribe(s =>
{
Console.WriteLine("doing something");
});
// simulate rapid firing event
for(int i = 0; i <= 100; i++)
generator.RaiseEvent(); 
// when no longer interested, dispose the subscription  
subscription.Dispose(); 
}
public class EventGenerator
{
public event EventHandler<bool> MyEvent;
public void RaiseEvent()
{
if (MyEvent != null)
{
MyEvent(this, false);
}
}
}

上面编码的Throttle运算符将允许一个值(事件)每秒为true。

因此,在上面的代码示例中,即使事件被多次触发,执行操作的文本也只会打印一次(一秒钟后)。

编辑
顺便说一句,绿线的原因是没有等待您的任务。要修复它,请将代码更改为:

protected async void DummyEventHandler(object sender, bool arg)
{
TotalCallActual++;
await LargeCPUBoundTask(); // there is no more green underline here
}

不幸的是,这仍然不能解决您的问题,因为无法等待事件,因此如果在LargeCPUBoundTask仍在运行时再次引发事件,则将对LargeCPUBoundTask进行另一次调用,因此如果您理解我的意思,则工作是重叠的。换句话说,这就是您的代码不起作用的原因。

我会使用计时器事件处理程序,而不是DummyEventHandler只需调整计时器的频率(毫秒),就可以了。您可以通过代码创建计时器,而无需将其作为控件添加到窗体中。我认为它在公共控件库中。

希望这能有所帮助。祝你好运

我花了更多的时间思考这个问题,我用第一个解决方案做出的假设是事件正在持续激发,而它可能只是在一段时间内激发一部分时间,然后在真实问题中停止。

在这种情况下,CPU绑定的任务只会在第一个事件触发时发生,然后如果事件在CPU绑定任务完成之前完成触发,则剩余的事件将不会得到处理。但你不想处理所有这些,只想处理"最后一个"(不一定是真正的最后一个,只想再处理一个来处理"清理")。

因此,我更新了我的答案,将频繁但间歇性(即突发事件然后安静)的用例包括在内——正确的事情会发生,CPU绑定任务的最终运行会发生(但一次运行的CPU绑定任务仍然不超过1个)。

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Sender s = new Sender();
using (Listener l = new Listener(s))
{
s.BeginDemonstration();
}
}
}
class Sender
{
const int ATTEMPTED_CALLS = 1000000;
internal EventHandler frequencyReducedHandler;
internal int actualCalls = 0;
internal int ignoredCalls = 0;
Task[] tasks = new Task[ATTEMPTED_CALLS];
internal void BeginDemonstration()
{
int attemptedCalls;
for (attemptedCalls = 0; attemptedCalls < ATTEMPTED_CALLS; attemptedCalls++)
{
tasks[attemptedCalls] = Task.Run(() => frequencyReducedHandler.Invoke(this, EventArgs.Empty));
//frequencyReducedHandler?.BeginInvoke(this, EventArgs.Empty, null, null);
}
if (tasks[0] != null)
{
Task.WaitAll(tasks, Timeout.Infinite);
}
Console.WriteLine($"Attempted: {attemptedCalls}tActual: {actualCalls}tIgnored: {ignoredCalls}");
Console.ReadKey();
}
}
class Listener : IDisposable
{
enum State
{
Waiting,
Running,
Queued
}
private readonly AutoResetEvent m_SingleEntry = new AutoResetEvent(true);
private readonly Sender m_Sender;
private int m_CurrentState = (int)State.Waiting;
internal Listener(Sender sender)
{
m_Sender = sender;
m_Sender.frequencyReducedHandler += Handler;
}
private async void Handler(object sender, EventArgs args)
{
int state = Interlocked.Increment(ref m_CurrentState);
try
{
if (state <= (int)State.Queued) // Previous state was WAITING or RUNNING
{
// Ensure only one run at a time
m_SingleEntry.WaitOne();
try
{
// Only one thread at a time here so
// no need for Interlocked.Increment
m_Sender.actualCalls++;
// Execute CPU intensive task
await Task.Delay(500);
}
finally
{
// Allow a waiting thread to proceed
m_SingleEntry.Set();
}
}
else
{
Interlocked.Increment(ref m_Sender.ignoredCalls);
}
}
finally
{
Interlocked.Decrement(ref m_CurrentState);
}
}
public void Dispose()
{
m_SingleEntry?.Dispose();
}
}

最新更新