检查状态(单线程)后,WCF通道是否可能出现故障?

ins*_*pid 5 .net c# wcf

我一直以这种方式处理通道的关闭和中止:

public async Task<MyDataContract> GetDataFromService()
{
    IClientChannel channel = null;
    try
    {
        IMyContract contract = factory.CreateChannel(address);
        MyDataContract returnValue = await player.GetMyDataAsync();
        channel = (IClientChannel);
        return returnValue;
    } 
    catch (CommunicationException)
    {
       // ex handling code
    } 
    finally
    {
        if (channel != null)
        {
            if (channel.State == CommunicationState.Faulted)
            {
                channel.Abort();
            }
            else
            {
                channel.Close();
            }
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设只有一个线程使用该通道.检查状态后,我们怎么知道通道不会出错?如果发生这样的事情,代码将尝试Close()和Close()将在finally块中抛出异常.关于为什么这是安全/不安全的解释以及更好,更安全的方式的例子将不胜感激.

Han*_*ney 2

是的,状态是您获取时当前状态的“快照”。在您访问 CommunicationState 和您根据它做出逻辑决策之间的时间里,状态很容易发生变化。更好的 WCF 模式是:

try
{
    // Open connection
    proxy.Open();

    // Do your work with the open connection here...
}
finally
{
    try
    {
        proxy.Close();
    }
    catch
    {
        // Close failed
        proxy.Abort();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样你就不会依赖国家来做出决定。您尝试做最有可能的事情(健康的关闭),如果失败(当 CommunicationState 出现故障时就会失败),您可以调用 Abort 以确保正确的清理。