在关闭超时时创建 WCF 客户端的新实例?

Create new instance of WCF client on closing timeout?

我有一个 class 用于创建我的 WCF 服务客户端。

是否可以在服务超时时创建新实例?我的意思是每次出去,关闭,打开,接收。但是Closing对我来说更重要。

如下:

public class ServiceClientFactory
{
    private static SmartServiceClient _client;
    internal SmartServiceClient Client
    {
        get
        {
            if (_client is not closed && _client != null) return _client;
            _client = new SmartServiceClient();
            return _client;
        }
    }
}

首先您需要修改工厂代码 - 您还需要检查 Faulted 状态:

if (_client != null) 
{
    if (_client.State == CommunicationState.Faulted)
    {
        _client.Abort(); // Use when channel is faulted
    }

    // Now you can check for closed state etc...
    else if (_client.State != CommunicationState.Closed)
    {
        return _client;
    }
}

_client = new SmartServiceClient();
return _client;

如果出现超时异常,通道将处于故障状态,因此下次您尝试让您的客户端...

var client = ServiceClientFactory.Client; // Client is renewed here.

...您将获得一个新实例。