DuplexChannelServiceClientWrapper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.ServiceModel;
  7. using Aitex.Core.RT.Log;
  8. using System.Threading;
  9. namespace Aitex.Core.WCF
  10. {
  11. public class DuplexChannelServiceClientWrapper<T>
  12. {
  13. DuplexChannelFactory<T> _factory;
  14. T _proxy;
  15. bool _isInError = false;
  16. string _serviceName;
  17. InstanceContext _callbackInstance;
  18. public DuplexChannelServiceClientWrapper(InstanceContext callbackInstance, string endpointConfigurationName, string name)
  19. {
  20. _serviceName = name;
  21. _callbackInstance = callbackInstance;
  22. try
  23. {
  24. _factory = new DuplexChannelFactory<T>(_callbackInstance, endpointConfigurationName);
  25. }
  26. catch (Exception ex)
  27. {
  28. MessageBox.Show("不能创建Service " + name + ",检查配置:" + endpointConfigurationName + ex.Message);
  29. LOG.Error("不能创建Service " + name + ",检查配置:" + endpointConfigurationName, ex);
  30. }
  31. }
  32. public void Invoke(Action<T> action)
  33. {
  34. if (_factory == null)
  35. return;
  36. if (_proxy == null)
  37. {
  38. _proxy = _factory.CreateChannel();
  39. }
  40. for (int i = 0; i < 2; i++)
  41. {
  42. if (Do(action))
  43. break;
  44. Thread.Sleep(10);
  45. }
  46. }
  47. bool Do(Action<T> action)
  48. {
  49. if (_proxy != null && ((IClientChannel)_proxy).State == CommunicationState.Faulted)
  50. {
  51. ((IClientChannel)_proxy).Abort();
  52. _proxy = _factory.CreateChannel();
  53. }
  54. try
  55. {
  56. action(_proxy);
  57. if (_isInError)
  58. {
  59. _isInError = false;
  60. LOG.Info(_serviceName + " 服务恢复");
  61. }
  62. return true;
  63. }
  64. catch (EndpointNotFoundException ex)
  65. {
  66. if (!_isInError)
  67. {
  68. _isInError = true;
  69. LOG.Error(_serviceName + " 连接已经断开.", ex);
  70. }
  71. }
  72. catch (ProtocolException ex)
  73. {
  74. if (!_isInError)
  75. {
  76. _isInError = true;
  77. LOG.Error(_serviceName + " 服务程序异常.", ex);
  78. }
  79. }
  80. catch (Exception ex)
  81. {
  82. if (!_isInError)
  83. {
  84. _isInError = true;
  85. LOG.Error(_serviceName + " 服务异常", ex);
  86. }
  87. }
  88. ((IClientChannel)_proxy).Abort();
  89. _proxy = _factory.CreateChannel();
  90. return false;
  91. }
  92. }
  93. }