Using Rx to call a WCF service method Async is causing Closure problems
I am currently using this code tu call a webservice to get data for an application page. Everything is fine until I try to call this method 10 times in a ro开发者_StackOverfloww without waiting for the first call to finish.
Doing so is causing me to have a problem with closures and I get the same result object for all my results.
has anyone faced this with Rx.Net before? if so does anyone have an idea or a lead so that I may resolve this issue.
public void GetPage(long pageId, Action<PageDTO> observer)
{
Observable.FromEvent<GetPageCompletedEventArgs>(
handler => Service.GetPageCompleted += handler,
handler => Service.GetPageCompleted -= handler)
.Select(eventHandler => eventHandler.EventArgs.Result)
.Take(1) // necessary to ensure the observable unsubscribes
.ObserveOnDispatcher() // controls which thread the observer runs on;
.Subscribe(observer, HandleError);
Service.GetPageAsync(pageId);
}
Is Service
always the same instance? If so, you're going to run into all kinds of craziness whereby GetPageCompleted
events will be handled by the FromEvent
created by a different call (with different arguments), which would explain why your results are the same for all methods that were called at the same time.
You can get around this specific issue by using the Begin/End methods, though you will still likely run into problems with contention on the underlying connection.
public void GetPage(long pageId, Action<PageDTO> observer)
{
Observable.FromAsyncPattern<long, PageDTO>(
service.BeginGetAwards, service.EndGetAwards)(pageId)
.ObserveOnDispatcher() // controls which thread the observer runs on;
.Subscribe(observer, HandleError);
}
精彩评论