c# - 双工 channel 故障事件不会在第二次连接尝试时出现

标签 c# .net wcf wcf-4 duplex-channel

我有常规的 net.tcp WCF 服务客户端和常规的 net.tcp duplex(即带有回调)WCF 服务客户端。我已经实现了一些逻辑,以在服务出现故障时不断地重新实例化连接。

它们的创建方式完全相同:

FooServiceClient Create()
{
    var client = new FooServiceClient(ChannelBinding);
    client.Faulted += this.FaultedHandler;
    client.Ping(); // An empty service function to make sure connection is OK
    return client;
}

BarServiceClient Create()
{
    var duplexClient = new BarServiceClient(new InstanceContext(this.barServiceCallback));
    duplexClient.Faulted += this.FaultedHandler;
    duplexClient.Ping(); // An empty service function to make sure connection is OK
    return duplexClient;
}

public class Watcher
{
public Watcher()
{
    this.CommunicationObject = this.Create();
}

ICommunicationObject CommunicationObject { get; private set; }

void FaultedHandler(object sender, EventArgs ea)
{
    this.CommunicationObject.Abort();
    this.CommunicationObject.Faulted -= this.FaultedHandler;
    this.CommunicationObject = this.Create();
}
}

FaultedHandler() 中止 channel 并使用上面的代码重新创建它。

FooServiceClient 重新连接逻辑工作得很好,它在多次故障后正在重新连接。然而,几乎相同但双工的 BarServiceClient 仅从第一个 BarServiceClient 实例接收 Faulted 事件,即 一次

为什么只有双工 BarServiceClient 的第一个实例得到错误事件?有任何解决方法吗?


类似的未回答问题:WCF Reliable session without transport security will not faulted event on time

最佳答案

经过两天与 WCF 的斗争后,我找到了解决方法。

有时 WCF 会触发 Faulted 事件,但有时不会。但是,Closed 事件始终会被触发,尤其是在 Abort() 调用之后。

所以我在 FaultedHandler 中调用了 Abort(),它有效地触发了 Closed 事件。随后,ClosedHandler 执行重新连接。如果 Faulted 从未被框架触发,则始终会触发 Closed 事件。

BarServiceClient Create()
{
    var duplexClient = new BarServiceClient(new InstanceContext(this.barServiceCallback));
    duplexClient.Faulted += this.FaultedHandler;
    duplexClient.Closed += this.ClosedHandler;
    duplexClient.Ping(); // An empty service function to make sure connection is OK
    return duplexClient;
}

public class Watcher
{
public Watcher()
{
    this.CommunicationObject = this.Create();
}

ICommunicationObject CommunicationObject { get; private set; }

void FaultedHandler(object sender, EventArgs ea)
{
    this.CommunicationObject.Abort();
}

void ClosedHandler(object sender, EventArgs ea)
{
    this.CommunicationObject.Faulted -= this.FaultedHandler;
    this.CommunicationObject.Closed -= this.ClosedHandler;
    this.CommunicationObject = this.Create();
}
}

关于c# - 双工 channel 故障事件不会在第二次连接尝试时出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10847877/

相关文章:

c# - 在 Visual Studio 2013 中查看受限的 WCF 调用

c# - 来自代码的 Wpf 动画

asp.net-mvc - MVC - 将 MVC 与 WCF 结合使用

WCF net.tcp 连接总是失败

c# - 在构建时将 ASPX 中的字符串替换为构建版本

c# - 在列表中查找项目的特定关键字

java - 通过 JAVA 使用 NTLM 身份验证访问 IIS WCF 服务

c# - 如何使用 HttpClient 返回 "refresh"cookie

c# - Winforms c# - 将焦点设置到 TabPage 的第一个子控件

c# - 代码首次尝试创建数据库时出现异常