由于 Silverlight 网络环境的异步特性,我建议您构建更多可测试的 ServiceAgent - 围绕 Silverlight 的客户端代理的长期单例包装器,并带有服务方法的回调。您可以在调用服务方法或使用通道故障事件之前检查真实代理状态(并在需要时重新创建)。例如:
public void GetOptionsAsync(Action<GetOptionsCompletedEventArgs> callback)
{
try
{
CheckProxy();
EventHandler<GetOptionsCompletedEventArgs> handler = null;
handler = (sender, args) =>
{
Proxy.GetOptionsCompleted -= handler;
if (args.Error != null)
{
//...
}
if (callback != null)
{
callback(args);
}
};
Proxy.GetOptionsCompleted += handler;
Proxy.GetOptionsAsync();
}
catch (Exception unknownException)
{
//...
throw;
}
}
public override void ResetProxy() //AbortProxy/CloseProxy
{
if (Proxy != null)
{
try
{
Proxy.CloseProxy(); //extension method to handle exception while closing
}
catch (Exception unknownException) //CommunicationObjectFaultedException
{
//...
Proxy.Abort();
}
}
CreateProxy();
}
public override void CheckProxy()
{
if (Proxy == null || (Proxy.State != CommunicationState.Opened && Proxy.State != CommunicationState.Created))
{
ResetProxy();
}
}
public override void CreateProxy() //RecreateProxy
{
Proxy = new WcfClient();
Proxy.InnerChannel.Faulted += OnChannelFaulted;
}