How to throttle the speed of an event without using Rx Framework(如何在不使用 Rx 框架的情况下限制事件的速度)
问题描述
我想限制事件的速度,如何在不使用 Microsoft Rx 框架的情况下实现这一点.我在 Rx 的帮助下完成了这项工作.但我正在尝试的是,我需要根据时隙限制 Map 的 View changed 事件.是否可以在不使用 Rx 的情况下实现相同的功能.
I want to throttle the speed of an event, How I can achieve this without using Microsoft Rx framework. I had done this with the help of Rx. But what I am trying is, I need to throttle Map's View changed event based on a time slot. Is it possible to implement the same without using Rx.
我不允许使用 Rx,我必须保持二进制大小尽可能小.
I am not allowed to use Rx and I have to keep the binary size as small as possible.
推荐答案
例如,如果您的事件是 EventHandler 类型,则此方法有效.它为你的事件处理程序创建了一个被限制的包装器:
This works, if your event is of type EventHandler<EventArgs> for example. It creates a wrapper for your event handler that is throttled:
private EventHandler<EventArgs> CreateThrottledEventHandler(
EventHandler<EventArgs> handler,
TimeSpan throttle)
{
bool throttling = false;
return (s,e) =>
{
if(throttling) return;
handler(s,e);
throttling = true;
Task.Delay(throttle).ContinueWith(_ => throttling = false);
};
}
像这样附加:
this.SomeEvent += CreateThrottledEventHandler(
(s,e) => Console.WriteLine("I am throttled!"),
TimeSpan.FromSeconds(5));
不过,如果您以后需要使用 -= 取消连接,则应该存储从 CreateThrottledEventHandler 返回的处理程序.
Although, you should store the handler returned from CreateThrottledEventHandler if you need to unwire it with -= later.
这篇关于如何在不使用 Rx 框架的情况下限制事件的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不使用 Rx 框架的情况下限制事件的速度
基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
