【发布时间】:2011-02-23 14:39:12
【问题描述】:
我有一个使用 Silverlight 4 中的 Observables 进行 WCF 调用的问题。 考虑下面的简单 Web 服务调用。
var adminclient = ServiceProxy.WithFactory<AuthenticationClient>();
var results= Observable.FromEvent<AuthorizeAdministratorCompletedEventArgs>(
s => adminclient.AuthorizeAdministratorCompleted += s,
s => adminclient.AuthorizeAdministratorCompleted -= s).ObserveOnDispatcher();
adminclient.AuthorizeAdministratorAsync();
results.Subscribe(e =>
{
//Enable UI Button
});
我已经实现了一个扩展方法,它包装了订阅方法,它在返回时进行了一些错误验证。
返回results.Subscribe(e =>
e is System.Collections.Generic.Event<AuthorizeAdministratorCompletedEventArgs>
几乎每个查询都会有不同的返回类型,例如:
e is System.Collections.Generic.Event<AsyncCompletedEventArgs>
如果我有一个看起来像这样的包装器,我如何将每种类型的 xxxCompletedEventArgs 转换为其基本类型 AsyncCompletedEventArgs 以便我可以访问 e .EventArgs 并检查 Error 属性
public static IDisposable Subscribe<TSource>(this IObservable<TSource> source, Action<TSource> onNext = null, Action onError = null, Action onFinal = null)
{
Action<TSource> onNextWrapper = (s) =>
{
var args = (System.Collections.Generic.IEvent<AsyncCompletedEventArgs>)s;
try
{
if (WCFExceptionHandler.HandleError(args.EventArgs))
{
if (onNext != null)
onNext(s);
}
else
{
if (onError != null)
onError();
}
}
finally
{
if (onFinal != null)
onFinal();
}
};
return source.Subscribe<TSource>(onNextWrapper, (e) => { throw e; });
}
上面的代码会失败
无法将 'System.Collections.Generic.Event1[MyProject.Provider.AuthorizeAdministratorCompletedEventArgs]' 类型的对象转换为类型 'System.Collections.Generic.IEvent1[System.ComponentModel.AsyncCompletedEventArgs]'
这是WCFExceptionHandler.HandleError(args.EventArgs))的方法定义
public static bool HandleError(AsyncCompletedEventArgs e)
【问题讨论】:
标签: silverlight silverlight-4.0 delegates system.reactive