我如何使用System.Linq.Observable.Throttle()

时间:2010-08-18 15:41:44

标签: c# linq system.reactive

我有以下代码使用System.Reactive中的Observable类。我正在使用2009年11月的Silverlight 3工具包。

private IObservable<Event<EventArgs>> _ob;
private IDisposable _proxy;
 ... 

private void Init()
{
  _ob = Observable
           .FromEvent<EventArgs>( x_Grid, "LayoutUpdated" )
           .Throttle( 2000 );  // *** <- The problem
  _proxy = _ob.Subscribe( () => { } );
}

代码段导致异常:

System.ObjectDisposedException: Cannot access a disposed object.
   at System.Threading.TimerBase.ChangeTimer(UInt32 dueTime, UInt32 period)
   at System.Threading.Timer.Change(Int32 dueTime, Int32 period)
   at System.Linq.Observable.<>c__DisplayClass175`2.<>c__DisplayClass17a.<Generate>b__173(Object _)
   at System.Threading._TimerCallback.TimerCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading._TimerCallback.PerformTimerCallback(Object state)

如果Throttle()方法不存在,代码可以正常工作。异常堆栈跟踪表示访问已处置的对象。我所知道的唯一一次性对象是Subscribe()调用返回的对象:但是这个没有被丢弃。

有人能用这段代码指出问题吗?

1 个答案:

答案 0 :(得分:1)

在InitializeComponent之前是否调用了Init()(即在正确加载Xaml之前?)你的代码看起来是正确的 - 如果不能修复它,我会说你应该升级到SL4(至少要尝试一下) RX)。

此外,在SilverLight中更实际地使用Rx是通过ReactiveXaml library(完全披露:我是作者)。