Tuesday, August 28, 2012

Throttling an event from a control in Silverlight

Throttling an event from a control in Silverlight

I have a Silverlight app that utilizes the Bing Maps control. Data loads when ever the maps view stops changing. I saw an example where someone used the ASP.Net version of the control and was able to acheive this. Is this same thing possible in Silverlight?

Microsoft.Maps.Events.addThrottledHandler(map, 'viewchangeend', UpdatePOIData, 250); 

Answers & Comments...

Answer: 1

You could do it with Reactive Extensions. The Throttle method exists for this purpose:

var observable =     Observable.FromEventPattern<MapEventArgs>(         handler => map.ViewChangeEnd += handler,         handler => map.ViewChangeEnd -= handler);  observable.Throttle(TimeSpan.FromSeconds(1))           .Subscribe(ev => map_ViewChangeEnd(ev.Sender, ev.EventArgs));   ...  void map_ViewChangeEnd(object sender, MapEventArgs e) {     ... } 

(untested)

by : Thomas Levesquehttp://stackoverflow.com/users/98713

Answer: 2

rx (unless Im behind) is not yet built into silverlight and seems a little overkill to have the client download all the rx dll just for throttling unless you are going to use it extensively.

At its simplest create your own throttling class using a dispatchtimer which takes the initial call waits x seconds and then checks if another call has come in since before executing your action.

Sorry I dont have any code to hand

by : Gingemonsterhttp://stackoverflow.com/users/352804

Answer: 3

To get around the "Invalid cross-thread access ( UnauthorizedAccessExcecption) while using Subscribe function" error you'll get using this code. Use the following:

using System.Reactive.Concurrency; using System.Reactive.Linq;  var observable = Observable.FromEventPattern<MapEventArgs>(handler => MyMap.ViewChangeEnd +=     handler, handler => MyMap.ViewChangeEnd -= handler); observable.Throttle(TimeSpan.FromSeconds(2)).ObserveOn(DispatcherScheduler.Current).Subscribe(ev => MyMap_ViewChangeEnd(ev.Sender, ev.EventArgs));  

You have to add the "ObserveOn(DispatcherScheduler.Current)" to make it work. And add references for System.Reactive.Core, System.Reactive.Interfaces, System.Reactive.Linq, System.Reactive.Windows.Threading.

by : Gary Woodhttp://stackoverflow.com/users/1630943




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog