WCF 服务代理 - Close() 和 Abort 函数都被调用

WCF Service proxy - Both Close() and Abort functions getting called

我有以下代码调用 WCF 代理:-

var client = new ServiceClientProxy(); 

try
 {

   var documents = client.GetDocuments();
   client.Close();

   if(documents.Length > 50)
   {
     throw new Exception("Too many Documents");
   }

  else if(documents.Length <10)
   {
     throw new Exception("Too many Documents");
   }

  else
   {
     return documents;
   }

 }

catch(exception ex)
{
  client.Abort();
}

此处如果我们从服务中获取的文档数大于 50 或小于 10,在这种情况下,我们将按预期方式调用 client.Is 上的 Close() 和 Abort 函数调用WCF 服务代理? 任何人请建议是否有更好的方法来处理这个问题。

另外,在调用后立即关闭客户端连接是更好的方法还是我们需要等到我们完全使用响应属性并在结束时关闭连接?

Also is it a better approach to close the client connection immediately after the call or do we need to wait till we have completely used the response properties and close the connection at end?

取决于您是否需要对该服务进行后续调用。如果不是那么一定要关闭连接。

Is this expected way of calling WCF service proxy? Anyone please suggest if there is some better way handling this.

没有。要处理内置于 WCF 中的问题,您实际上应该采用如下结构:

  Documents documnts = null;

     try
     {
          var client = new ServiceClientProxy();
          documents = client.GetDocuments();
     }
     finally
     {
         try
         {
            if (client.State != CommunicationState.Closed)
                 client.Close();
          }
          catch
          {
             client.Abort();
          };
    };

    if (documents.Length > 50)
    {
        throw new Exception("Too many Documents");
    }
    else if (documents.Length < 10)
    {
        throw new Exception("Too many Documents");
    }
    else
    {
       return documents;
    }

如果您想真正理解 'why' 我强烈建议您阅读本系列文章。他们将清除您问题的关闭/中止部分。

http://blogs.msmvps.com/p3net/2014/02/02/a-smarter-wcf-service-client-part-1/
http://blogs.msmvps.com/p3net/2014/02/09/a-smarter-wcf-service-client-part-2/
http://blogs.msmvps.com/p3net/2014/02/23/a-smarter-wcf-service-client-part-3/
http://blogs.msmvps.com/p3net/2014/03/15/a-smarter-wcf-service-client-part-4/

关于您提供的代码我应该指出的另一件事是异常应该是异常的。

对我认为是业务逻辑的内容使用异常通常不是正确的做法。考虑一下 return 结构化结果的方法。也许在你的情况下它是有道理的。

HTH