c# - 处理 WCF 超时的最佳方法

标签 c# .net wcf web-services

我有一个实时应用程序可以跟踪全国多个站点的 Assets 。作为此解决方案的一部分,我有 8 个更新中央服务器的客户端应用程序。

我的问题是,有时应用程序会失去与中央服务器的连接,我想知道处理此问题的最佳方法是什么?我知道我可以增加最大发送/接收时间来处理超时但是我也想要一个优雅的解决方案来处理如果与服务器的连接断开:

例如,我这样调用我的服务:

using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
    statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}

我正在考虑添加一个 try/catch 所以...

using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
    try
    {
       statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
    }
    catch (TimeoutException timeout)
    {
       LogMessage(timeout);
    }
    catch (CommunicationException comm)
    {
       LogMessage(comm);
    }
}

以这种方式处理它不允许我在没有大量代码重复的情况下重新运行代码。有人有什么建议吗?

编辑:查看具有整体解决方案的 Sixto Saez 和 user24601 答案比在单个异常级别处理超时要好但是......我认为下面会解决我的问题(但它会增加 TON额外的代码错误处理):

void Method(int statusId)
{
     var statusRepository = new StatusRepositoryClient.StatusRepositoryClient()

      try
      {
         IsServerUp();
         statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
         statusRepository.Close(); 
      }            
      catch (Exception ex)
      {
            statusRepository.Abort();

            if (ex is TimeoutException || ex is CommunicationException)
            {
              LogMessage(timeout);
              Method(statusId);
            }
            else
            {
                throw new Exception(ex.Message + ex.InnerException);
            }
        }

  }
}

bool IsServerUp()
{
    var x = new Ping();
    var reply = x.Send(IPAddress.Parse("127.0.0.1"));

    if (reply == null)
    {
       IsServerUp();
    }
    else
    {
       if (reply.Status != IPStatus.Success)
       {
          IsServerUp();
       }
    }

    return true;
}

最佳答案

对于初学者,我认为您的 Wcf 错误处理是错误的。它应该是这样的

var statusRepository = new StatusRepositoryClient.StatusRepositoryClient();
try
{
    statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
    statusRepository.Close()
}
catch(Exception e)
{
   statusRepository.Abort();
   LogMessage(e);
   throw; //I would do this to let user know.
}

我也会重新抛出错误让用户知道这个问题。

关于c# - 处理 WCF 超时的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6521197/

相关文章:

c# - 在 OSX 上使用 MonoKickstart 时找不到 gdiplus.dll

.net - 适用于 Windows 98 的 .NET 2.0 应用程序安装程序

c# - AutoMapper 不映射子属性

asp.net - Wcf - 已超出传入消息 (65536) 的最大消息大小配额?

c# - 缺少“管理私钥”选项

c# - 从 3 个通用类型中推断出 2 个

c# - XML Xpath 表达式

c# - 所有的逻辑应该写在 Controller 里面?

c# - 如何正确使用 Task.ContinueWith?

.net - 如何以编程方式检查 WCF Http/Non-Http 激活组件?