Sic.Framework-Nanjing-Baishi/MECF.Framework.Common/Aitex/Core/WCF/ServiceClientWrapper.cs

139 lines
2.9 KiB
C#
Raw Normal View History

2023-04-13 11:51:03 +08:00
using System;
using System.ServiceModel;
using System.Threading;
using System.Windows;
using Aitex.Core.RT.Log;
using Aitex.Core.Utilities;
namespace Aitex.Core.WCF
{
public abstract class ServiceClientWrapper<T>
2023-04-13 11:51:03 +08:00
{
#region Variables
2023-04-13 11:51:03 +08:00
private readonly ChannelFactory<T> _factory;
private readonly string _serviceName;
2023-04-13 11:51:03 +08:00
private T _proxy;
private bool _isInError;
private bool _isAbortByUser;
private Retry _retryConnect = new();
#endregion
2023-04-13 11:51:03 +08:00
#region Constructors
2023-04-13 11:51:03 +08:00
protected ServiceClientWrapper(string endpointConfigurationName, string name)
2023-04-13 11:51:03 +08:00
{
_serviceName = name;
try
{
_factory = new ChannelFactory<T>(endpointConfigurationName);
}
catch (Exception ex)
{
MessageBox.Show("不能创建Service " + name + ",检查配置:" + endpointConfigurationName);
LOG.Error("不能创建Service " + name + ",检查配置:" + endpointConfigurationName, ex);
}
}
protected ServiceClientWrapper(string endpointConfigurationName, string name, EndpointAddress address)
2023-04-13 11:51:03 +08:00
{
_serviceName = name;
try
{
_factory = new ChannelFactory<T>(endpointConfigurationName, address);
}
catch (Exception ex)
{
MessageBox.Show("不能创建Service " + name + ",检查配置:" + endpointConfigurationName);
LOG.Error("不能创建Service " + name + ",检查配置:" + endpointConfigurationName, ex);
}
}
#endregion
#region Properties
public bool ActionFailed => _isInError;
#endregion
#region Methods
/// <summary>
/// 执行指定的方法。
/// </summary>
/// <param name="action"></param>
protected void Invoke(Action<T> action)
2023-04-13 11:51:03 +08:00
{
if (_factory == null)
return;
_proxy ??= _factory.CreateChannel();
for (var i = 0; i < 2; i++)
2023-04-13 11:51:03 +08:00
{
if (Do(action))
break;
2023-04-13 11:51:03 +08:00
Thread.Sleep(10);
}
}
private bool Do(Action<T> action)
{
if (_proxy != null && ((IClientChannel)_proxy).State == CommunicationState.Faulted)
2023-04-13 11:51:03 +08:00
{
((IClientChannel)_proxy).Abort();
2023-04-13 11:51:03 +08:00
_proxy = _factory.CreateChannel();
}
try
{
action(_proxy);
if (_isInError)
{
_isInError = false;
LOG.Info(_serviceName + " 服务恢复", isTraceOn: false);
}
return true;
}
catch (EndpointNotFoundException ex)
{
if (!_isInError)
{
_isInError = true;
LOG.Error(_serviceName + " 连接已经断开.", ex);
}
}
catch (ProtocolException ex2)
{
if (!_isInError)
{
_isInError = true;
LOG.Error(_serviceName + " 服务程序异常.", ex2);
}
}
catch (Exception ex3)
{
if (_isAbortByUser)
{
_isAbortByUser = false;
return true;
}
2023-04-13 11:51:03 +08:00
if (!_isInError)
{
_isInError = true;
LOG.Error(_serviceName + " 服务异常", ex3);
}
}
((IClientChannel)_proxy)?.Abort();
2023-04-13 11:51:03 +08:00
_proxy = _factory.CreateChannel();
return false;
}
#endregion
2023-04-13 11:51:03 +08:00
}
}