仅当在 C#/WPF 中未在给定时间内触发事件时才执行事件
Execute an event only if it wasn't fired for a given amount of time in C#/WPF
我有一个带有 MouseWheel 事件的 WPF 应用程序。本次活动的操作相当繁重。所以,我只想在用户停止滚动时执行此事件(即:如果他在给定的时间内没有滚动)。
在 JS 中,这很容易,我可以将 setTimout
放在一个 var 中,然后如果在 [=12] 执行之前发生另一个滚动,则对该 var 执行 clearTimeout
=](例如,这对于自动完成非常有用)。
如何在 c#
中实现?
类似下面的内容可能适合您的需要
public class perRxTickBuffer<T>
{
private readonly Subject<T> _innerSubject = new Subject<T>();
public perRxTickBuffer(TimeSpan? interval = null)
{
if (interval == null)
{
interval = TimeSpan.FromSeconds(1);
}
Output = _innerSubject.Sample(interval.Value);
}
public void Tick(T item)
{
_innerSubject.OnNext(item);
}
public IObservable<T> Output { get; }
}
创建一个实例,其中 T 是您的事件的事件参数类型。
设置一个适当的时间跨度值 - 对于您的情况可能是 1/4 秒。
只需从您的事件处理程序调用 Tick()
,然后订阅 Output
可观察对象以获得 'events'.
的规范流程
使用 Microsoft 的 Reactive Framework(又名 Rx)- NuGet System.Reactive.Windows.Threading
(对于 WPF)并添加 using System.Reactive.Linq;
非常容易 - 然后您可以这样做:
IObservable<EventPattern<MouseWheelEventArgs>> query =
Observable
.FromEventPattern<MouseWheelEventHandler, MouseWheelEventArgs>(
h => ui.MouseWheel += h, h => ui.MouseWheel -= h)
.Throttle(TimeSpan.FromMilliseconds(250.0))
.ObserveOnDispatcher();
IDisposable subscription =
query
.Subscribe(x =>
{
/* run expensive code */
});
文档是这样说的 Throttle
:
Ignores the values from an observable sequence which are followed by another value before due time with the specified source and dueTime.
我有一个带有 MouseWheel 事件的 WPF 应用程序。本次活动的操作相当繁重。所以,我只想在用户停止滚动时执行此事件(即:如果他在给定的时间内没有滚动)。
在 JS 中,这很容易,我可以将 setTimout
放在一个 var 中,然后如果在 [=12] 执行之前发生另一个滚动,则对该 var 执行 clearTimeout
=](例如,这对于自动完成非常有用)。
如何在 c#
中实现?
类似下面的内容可能适合您的需要
public class perRxTickBuffer<T>
{
private readonly Subject<T> _innerSubject = new Subject<T>();
public perRxTickBuffer(TimeSpan? interval = null)
{
if (interval == null)
{
interval = TimeSpan.FromSeconds(1);
}
Output = _innerSubject.Sample(interval.Value);
}
public void Tick(T item)
{
_innerSubject.OnNext(item);
}
public IObservable<T> Output { get; }
}
创建一个实例,其中 T 是您的事件的事件参数类型。
设置一个适当的时间跨度值 - 对于您的情况可能是 1/4 秒。
只需从您的事件处理程序调用 Tick()
,然后订阅 Output
可观察对象以获得 'events'.
使用 Microsoft 的 Reactive Framework(又名 Rx)- NuGet System.Reactive.Windows.Threading
(对于 WPF)并添加 using System.Reactive.Linq;
非常容易 - 然后您可以这样做:
IObservable<EventPattern<MouseWheelEventArgs>> query =
Observable
.FromEventPattern<MouseWheelEventHandler, MouseWheelEventArgs>(
h => ui.MouseWheel += h, h => ui.MouseWheel -= h)
.Throttle(TimeSpan.FromMilliseconds(250.0))
.ObserveOnDispatcher();
IDisposable subscription =
query
.Subscribe(x =>
{
/* run expensive code */
});
文档是这样说的 Throttle
:
Ignores the values from an observable sequence which are followed by another value before due time with the specified source and dueTime.