提交位移台和对焦系统代码
This commit is contained in:
@@ -0,0 +1,654 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using HardwareControl.Core.AxisPlatform;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
/// <summary>
|
||||
/// 位移台服务实现:AxisPlatform2.dll 负责串口与协议,
|
||||
/// 本类负责串口参数解析、调用串行化、错误映射与日志。
|
||||
/// </summary>
|
||||
public sealed class AxisStageService : IAxisStageService
|
||||
{
|
||||
// 系统参数中保存位移台串口的配置名称
|
||||
private const string ComPortConfigName = "translation_com";
|
||||
|
||||
private readonly AxisStageOptions _options;
|
||||
private readonly ILogger<AxisStageService> _logger;
|
||||
private readonly ISystemConfigService? _systemConfig;
|
||||
|
||||
// 串行化所有原生调用,DLL 句柄不支持并发访问
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
private IntPtr _handle = IntPtr.Zero;
|
||||
private volatile bool _connected;
|
||||
private volatile string? _portName;
|
||||
private bool _disposed;
|
||||
|
||||
public AxisStageService(
|
||||
IOptions<AxisStageOptions> options,
|
||||
ILogger<AxisStageService> logger,
|
||||
ISystemConfigService? systemConfig = null)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_systemConfig = systemConfig;
|
||||
}
|
||||
|
||||
public bool IsConnected => _connected;
|
||||
|
||||
public string? PortName => _portName;
|
||||
|
||||
public event EventHandler<AxisStageStatusChangedEventArgs>? StatusChanged;
|
||||
|
||||
// ---------- 连接 ----------
|
||||
|
||||
public async Task ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (_connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectCore()
|
||||
{
|
||||
var port = ResolvePort();
|
||||
var limitsPointer = IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
if (_options.Limits is { } limits)
|
||||
{
|
||||
var native = limits.ToNative();
|
||||
limitsPointer = Marshal.AllocHGlobal(Marshal.SizeOf<Axis2Limits>());
|
||||
Marshal.StructureToPtr(native, limitsPointer, false);
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"正在打开位移台串口 {Port}(帧头 {FrameHead})",
|
||||
port,
|
||||
_options.FrameHead);
|
||||
|
||||
var handle = AxisPlatformNative.axis_init(
|
||||
port,
|
||||
(byte)_options.FrameHead,
|
||||
limitsPointer);
|
||||
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
$"打开位移台串口 {port} 失败:串口不存在或被占用");
|
||||
}
|
||||
|
||||
_handle = handle;
|
||||
_connected = true;
|
||||
_portName = port;
|
||||
|
||||
_logger.LogInformation("位移台串口已打开:{Port}", port);
|
||||
StatusChanged?.Invoke(
|
||||
this,
|
||||
new AxisStageStatusChangedEventArgs(true, $"位移台已连接:{port}"));
|
||||
}
|
||||
catch (HardwareException)
|
||||
{
|
||||
ResetConnectionState();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is DllNotFoundException
|
||||
or BadImageFormatException
|
||||
or EntryPointNotFoundException)
|
||||
{
|
||||
ResetConnectionState();
|
||||
_logger.LogError(ex, "加载 AxisPlatform2.dll 失败");
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
BuildNativeLoadFailureMessage(ex),
|
||||
ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ResetConnectionState();
|
||||
_logger.LogError(ex, "打开位移台串口时发生未预期异常");
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
"连接位移台失败",
|
||||
ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (limitsPointer != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeHGlobal(limitsPointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 串口优先取系统参数 translation_com;为空时回退到 appsettings 的 AxisStage:ComPort。
|
||||
/// </summary>
|
||||
private string ResolvePort()
|
||||
{
|
||||
string? configured = null;
|
||||
|
||||
try
|
||||
{
|
||||
configured = _systemConfig?
|
||||
.GetAll()
|
||||
.FirstOrDefault(config => string.Equals(
|
||||
config.ConfigName,
|
||||
ComPortConfigName,
|
||||
StringComparison.OrdinalIgnoreCase))?
|
||||
.ConfigValue?
|
||||
.Trim();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", ComPortConfigName);
|
||||
}
|
||||
|
||||
var port = !string.IsNullOrWhiteSpace(configured)
|
||||
? configured
|
||||
: _options.ComPort?.Trim();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(port))
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"未配置位移台串口:请先在系统参数中添加 {ComPortConfigName}(例如 COM5)");
|
||||
}
|
||||
|
||||
return SerialPortNames.Normalize(port);
|
||||
}
|
||||
|
||||
// ---------- 断开 ----------
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var wasConnected = _connected;
|
||||
CloseHandle();
|
||||
|
||||
if (wasConnected)
|
||||
{
|
||||
_logger.LogInformation("位移台串口已关闭");
|
||||
StatusChanged?.Invoke(
|
||||
this,
|
||||
new AxisStageStatusChangedEventArgs(false, "位移台已断开"));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseHandle()
|
||||
{
|
||||
var handle = _handle;
|
||||
ResetConnectionState();
|
||||
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
AxisPlatformNative.axis_close(handle);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "关闭位移台串口时发生异常");
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetConnectionState()
|
||||
{
|
||||
_handle = IntPtr.Zero;
|
||||
_connected = false;
|
||||
_portName = null;
|
||||
}
|
||||
|
||||
// ---------- 运动 ----------
|
||||
|
||||
public async Task MoveXAsync(
|
||||
int distanceMm,
|
||||
int? speed = null,
|
||||
int? accel = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var distance = ToDistance(distanceMm, "X");
|
||||
var (speedValue, accelValue) = ResolveMotion(speed, accel);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_x_move(
|
||||
handle, distance, speedValue, accelValue);
|
||||
EnsureSuccess(handle, result, $"X 轴移动 {distance}mm");
|
||||
|
||||
_logger.LogInformation(
|
||||
"位移台 X 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
|
||||
distance,
|
||||
speedValue,
|
||||
accelValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MoveYAsync(
|
||||
int distanceMm,
|
||||
int? speed = null,
|
||||
int? accel = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var distance = ToDistance(distanceMm, "Y");
|
||||
var (speedValue, accelValue) = ResolveMotion(speed, accel);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_y_move(
|
||||
handle, distance, speedValue, accelValue);
|
||||
EnsureSuccess(handle, result, $"Y 轴移动 {distance}mm");
|
||||
|
||||
_logger.LogInformation(
|
||||
"位移台 Y 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
|
||||
distance,
|
||||
speedValue,
|
||||
accelValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MoveZAsync(
|
||||
int distanceMm,
|
||||
int? speed = null,
|
||||
int? accel = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var distance = ToDistance(distanceMm, "Z");
|
||||
var (speedValue, accelValue) = ResolveMotion(speed, accel);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_z_move(
|
||||
handle, distance, speedValue, accelValue);
|
||||
EnsureSuccess(handle, result, $"Z 轴移动 {distance}mm");
|
||||
|
||||
_logger.LogInformation(
|
||||
"位移台 Z 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
|
||||
distance,
|
||||
speedValue,
|
||||
accelValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MoveRelativeAsync(
|
||||
AxisStagePoint delta,
|
||||
int? speed = null,
|
||||
int? accel = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var (speedValue, accelValue) = ResolveMotion(speed, accel);
|
||||
var x = ToParams(delta.X, speedValue, accelValue, "X");
|
||||
var y = ToParams(delta.Y, speedValue, accelValue, "Y");
|
||||
var z = ToParams(delta.Z, speedValue, accelValue, "Z");
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_xyz_rel_move(
|
||||
handle, ref x, ref y, ref z);
|
||||
EnsureSuccess(
|
||||
handle,
|
||||
result,
|
||||
$"三轴相对运动(X={delta.X},Y={delta.Y},Z={delta.Z})");
|
||||
|
||||
_logger.LogInformation(
|
||||
"位移台三轴相对运动:X={X},Y={Y},Z={Z},速度 {Speed},加速度 {Accel}",
|
||||
delta.X,
|
||||
delta.Y,
|
||||
delta.Z,
|
||||
speedValue,
|
||||
accelValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MoveAbsoluteAsync(
|
||||
AxisStagePoint target,
|
||||
int? speed = null,
|
||||
int? accel = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var (speedValue, accelValue) = ResolveMotion(speed, accel);
|
||||
var x = ToParams(target.X, speedValue, accelValue, "X");
|
||||
var y = ToParams(target.Y, speedValue, accelValue, "Y");
|
||||
var z = ToParams(target.Z, speedValue, accelValue, "Z");
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_xyz_abs_move(
|
||||
handle, ref x, ref y, ref z);
|
||||
EnsureSuccess(
|
||||
handle,
|
||||
result,
|
||||
$"三轴绝对运动(X={target.X},Y={target.Y},Z={target.Z})");
|
||||
|
||||
_logger.LogInformation(
|
||||
"位移台三轴绝对运动:X={X},Y={Y},Z={Z},速度 {Speed},加速度 {Accel}",
|
||||
target.X,
|
||||
target.Y,
|
||||
target.Z,
|
||||
speedValue,
|
||||
accelValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 状态 ----------
|
||||
|
||||
public async Task<AxisStageStatus> ReadStatusAsync(
|
||||
int? timeoutMs = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
|
||||
var timeout = timeoutMs ?? _options.ReadTimeoutMs;
|
||||
if (timeout <= 0)
|
||||
{
|
||||
timeout = 1000;
|
||||
}
|
||||
|
||||
return await Task.Run(
|
||||
() => ReadStatusCore(handle, timeout, ct),
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private AxisStageStatus ReadStatusCore(
|
||||
IntPtr handle,
|
||||
int timeoutMs,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// 丢弃旧缓存,确保读到的是设备新上传的帧
|
||||
AxisPlatformNative.axis_flush(handle);
|
||||
|
||||
var deadline = Environment.TickCount64 + timeoutMs;
|
||||
var retryInterval = Math.Clamp(_options.ReadRetryIntervalMs, 10, 1000);
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = AxisPlatformNative.axis_read_upload(handle, out var data);
|
||||
if (result == AxisPlatformNative.Ok)
|
||||
{
|
||||
var status = MapStatus(data);
|
||||
|
||||
_logger.LogDebug(
|
||||
"位移台状态:X={X},Y={Y},Z={Z},运动中={Moving},设备错误={Error}",
|
||||
status.XPosition,
|
||||
status.YPosition,
|
||||
status.ZPosition,
|
||||
status.AnyMoving,
|
||||
status.DeviceError);
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
// 未收到数据/未找到上传帧时在超时时间内重试,其余错误立即抛出
|
||||
if (result is not (AxisPlatformNative.ErrTimeout
|
||||
or AxisPlatformNative.ErrParseFailed))
|
||||
{
|
||||
throw MapNativeError(handle, result, "读取位移台状态");
|
||||
}
|
||||
|
||||
if (Environment.TickCount64 >= deadline)
|
||||
{
|
||||
var detail = result == AxisPlatformNative.ErrTimeout
|
||||
? "未收到任何数据"
|
||||
: "未找到有效的上传帧";
|
||||
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.Timeout,
|
||||
$"读取位移台状态超时({timeoutMs}ms):{detail}");
|
||||
}
|
||||
|
||||
Thread.Sleep(retryInterval);
|
||||
}
|
||||
}
|
||||
|
||||
private static AxisStageStatus MapStatus(Axis2UploadData data) =>
|
||||
new(
|
||||
data.XPos,
|
||||
data.YPos,
|
||||
data.ZPos,
|
||||
data.XSta != 0,
|
||||
data.YSta != 0,
|
||||
data.ZSta != 0,
|
||||
data.SysSta != 0,
|
||||
data.Error,
|
||||
data.HwVersion,
|
||||
data.SwVersion,
|
||||
DateTimeOffset.Now);
|
||||
|
||||
// ---------- 参数校验与错误映射 ----------
|
||||
|
||||
private (ushort Speed, ushort Accel) ResolveMotion(int? speed, int? accel)
|
||||
{
|
||||
var speedValue = speed ?? _options.DefaultSpeed;
|
||||
var accelValue = accel ?? _options.DefaultAccel;
|
||||
|
||||
if (speedValue is <= 0 or > ushort.MaxValue)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"运行速度 {speedValue} 超出范围(1~{ushort.MaxValue})");
|
||||
}
|
||||
|
||||
if (accelValue is <= 0 or > ushort.MaxValue)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"加速度 {accelValue} 超出范围(1~{ushort.MaxValue})");
|
||||
}
|
||||
|
||||
return ((ushort)speedValue, (ushort)accelValue);
|
||||
}
|
||||
|
||||
private static short ToDistance(int value, string axis)
|
||||
{
|
||||
if (value is < short.MinValue or > short.MaxValue)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"{axis} 轴位移 {value}mm 超出范围({short.MinValue}~{short.MaxValue})");
|
||||
}
|
||||
|
||||
return (short)value;
|
||||
}
|
||||
|
||||
private static Axis2MoveParams ToParams(
|
||||
int value,
|
||||
ushort speed,
|
||||
ushort accel,
|
||||
string axis) => new()
|
||||
{
|
||||
Distance = ToDistance(value, axis),
|
||||
Speed = speed,
|
||||
Accel = accel,
|
||||
};
|
||||
|
||||
/// <summary>文档中运动函数的返回值可能为发送字节数,非负均视为成功。</summary>
|
||||
private static void EnsureSuccess(IntPtr handle, int result, string operation)
|
||||
{
|
||||
if (result >= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw MapNativeError(handle, result, operation);
|
||||
}
|
||||
|
||||
private static HardwareException MapNativeError(
|
||||
IntPtr handle,
|
||||
int code,
|
||||
string operation)
|
||||
{
|
||||
var kind = code switch
|
||||
{
|
||||
AxisPlatformNative.ErrNullPtr => HardwareErrorKind.InvalidArgument,
|
||||
AxisPlatformNative.ErrBufTooSmall => HardwareErrorKind.InvalidArgument,
|
||||
AxisPlatformNative.ErrFrameTooShort => HardwareErrorKind.CommunicationFailed,
|
||||
AxisPlatformNative.ErrComOpenFailed => HardwareErrorKind.ConnectFailed,
|
||||
AxisPlatformNative.ErrComNotOpen => HardwareErrorKind.NotConnected,
|
||||
AxisPlatformNative.ErrComSendFailed => HardwareErrorKind.CommunicationFailed,
|
||||
AxisPlatformNative.ErrParseFailed => HardwareErrorKind.CommunicationFailed,
|
||||
AxisPlatformNative.ErrTimeout => HardwareErrorKind.Timeout,
|
||||
_ => HardwareErrorKind.Unknown,
|
||||
};
|
||||
|
||||
var hint = code switch
|
||||
{
|
||||
AxisPlatformNative.ErrComOpenFailed => "(串口不存在或被占用)",
|
||||
AxisPlatformNative.ErrComNotOpen => "(串口尚未打开)",
|
||||
AxisPlatformNative.ErrComSendFailed => "(可能是超出限位或串口发送失败)",
|
||||
AxisPlatformNative.ErrParseFailed => "(CRC 校验失败或帧格式错误)",
|
||||
AxisPlatformNative.ErrTimeout => "(未在指定时间内收到数据)",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
var detail = AxisPlatformNative.GetError(handle);
|
||||
var message = string.IsNullOrWhiteSpace(detail)
|
||||
? $"{operation}失败{hint}(错误码 {code})"
|
||||
: $"{operation}失败{hint}(错误码 {code}):{detail}";
|
||||
|
||||
return new HardwareException(kind, message);
|
||||
}
|
||||
|
||||
private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch
|
||||
{
|
||||
DllNotFoundException =>
|
||||
"加载 AxisPlatform2.dll 失败:请确认该 DLL 已复制到程序输出目录"
|
||||
+ $"(当前目录:{AppContext.BaseDirectory})",
|
||||
BadImageFormatException =>
|
||||
"加载 AxisPlatform2.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行",
|
||||
EntryPointNotFoundException =>
|
||||
"加载 AxisPlatform2.dll 失败:DLL 版本与接口声明不匹配",
|
||||
_ => "加载 AxisPlatform2.dll 失败",
|
||||
};
|
||||
|
||||
// ---------- 释放 ----------
|
||||
|
||||
private IntPtr RequireHandle()
|
||||
{
|
||||
var handle = _handle;
|
||||
if (!_connected || handle == IntPtr.Zero)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.NotConnected,
|
||||
"位移台尚未连接,请先调用连接接口");
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _gate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
CloseHandle();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
_gate.Dispose();
|
||||
}
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
using HardwareControl.Core.FocusSystem;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
/// <summary>
|
||||
/// 定焦系统服务实现:FocusSystem2.dll 负责串口与协议,
|
||||
/// 本类负责串口参数解析、调用串行化、错误映射与日志。
|
||||
/// </summary>
|
||||
public sealed class FocusSystemService : IFocusSystemService
|
||||
{
|
||||
// 系统参数中保存对焦硬件串口的配置名称
|
||||
private const string ComPortConfigName = "focus_com";
|
||||
|
||||
private readonly FocusSystemOptions _options;
|
||||
private readonly ILogger<FocusSystemService> _logger;
|
||||
private readonly ISystemConfigService? _systemConfig;
|
||||
|
||||
// 串行化所有原生调用,DLL 句柄不支持并发访问
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
private IntPtr _handle = IntPtr.Zero;
|
||||
private volatile bool _connected;
|
||||
private volatile string? _portName;
|
||||
private bool _disposed;
|
||||
|
||||
public FocusSystemService(
|
||||
IOptions<FocusSystemOptions> options,
|
||||
ILogger<FocusSystemService> logger,
|
||||
ISystemConfigService? systemConfig = null)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_systemConfig = systemConfig;
|
||||
}
|
||||
|
||||
public bool IsConnected => _connected;
|
||||
|
||||
public string? PortName => _portName;
|
||||
|
||||
public event EventHandler<FocusSystemStatusChangedEventArgs>? StatusChanged;
|
||||
|
||||
// ---------- 连接 ----------
|
||||
|
||||
public async Task ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (_connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectCore()
|
||||
{
|
||||
var port = ResolvePort();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("正在打开对焦系统串口 {Port}", port);
|
||||
|
||||
var handle = FocusSystemNative.focus_init(port);
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
$"打开对焦系统串口 {port} 失败:串口不存在或被占用");
|
||||
}
|
||||
|
||||
_handle = handle;
|
||||
_connected = true;
|
||||
_portName = port;
|
||||
|
||||
_logger.LogInformation("对焦系统串口已打开:{Port}", port);
|
||||
StatusChanged?.Invoke(
|
||||
this,
|
||||
new FocusSystemStatusChangedEventArgs(true, $"对焦系统已连接:{port}"));
|
||||
}
|
||||
catch (HardwareException)
|
||||
{
|
||||
ResetConnectionState();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is DllNotFoundException
|
||||
or BadImageFormatException
|
||||
or EntryPointNotFoundException)
|
||||
{
|
||||
ResetConnectionState();
|
||||
_logger.LogError(ex, "加载 FocusSystem2.dll 失败");
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
BuildNativeLoadFailureMessage(ex),
|
||||
ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ResetConnectionState();
|
||||
_logger.LogError(ex, "打开对焦系统串口时发生未预期异常");
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed,
|
||||
"连接对焦系统失败",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 串口优先取系统参数 focus_com;为空时回退到 appsettings 的 FocusSystem:ComPort。
|
||||
/// </summary>
|
||||
private string ResolvePort()
|
||||
{
|
||||
string? configured = null;
|
||||
|
||||
try
|
||||
{
|
||||
configured = _systemConfig?
|
||||
.GetAll()
|
||||
.FirstOrDefault(config => string.Equals(
|
||||
config.ConfigName,
|
||||
ComPortConfigName,
|
||||
StringComparison.OrdinalIgnoreCase))?
|
||||
.ConfigValue?
|
||||
.Trim();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", ComPortConfigName);
|
||||
}
|
||||
|
||||
var port = !string.IsNullOrWhiteSpace(configured)
|
||||
? configured
|
||||
: _options.ComPort?.Trim();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(port))
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"未配置对焦系统串口:请先在系统参数中添加 {ComPortConfigName}(例如 COM6)");
|
||||
}
|
||||
|
||||
return SerialPortNames.Normalize(port);
|
||||
}
|
||||
|
||||
// ---------- 断开 ----------
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var wasConnected = _connected;
|
||||
CloseHandle();
|
||||
|
||||
if (wasConnected)
|
||||
{
|
||||
_logger.LogInformation("对焦系统串口已关闭");
|
||||
StatusChanged?.Invoke(
|
||||
this,
|
||||
new FocusSystemStatusChangedEventArgs(false, "对焦系统已断开"));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseHandle()
|
||||
{
|
||||
var handle = _handle;
|
||||
ResetConnectionState();
|
||||
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
FocusSystemNative.focus_close(handle);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "关闭对焦系统串口时发生异常");
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetConnectionState()
|
||||
{
|
||||
_handle = IntPtr.Zero;
|
||||
_connected = false;
|
||||
_portName = null;
|
||||
}
|
||||
|
||||
// ---------- 命令 ----------
|
||||
|
||||
public Task StartSingleFocusAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_single_focus, "单次对焦", ct);
|
||||
|
||||
public Task StartContinuousFocusAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_continuous_focus, "连续对焦", ct);
|
||||
|
||||
public Task EnterCalibrationModeAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_calib_mode, "进入校准模式", ct);
|
||||
|
||||
public Task MoveCalibrationAsync(
|
||||
int distanceMm,
|
||||
int? speed = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var distance = ToInt8(distanceMm, "校准位移");
|
||||
var speedValue = speed ?? _options.DefaultCalibrationSpeed;
|
||||
if (speedValue is <= 0 or > ushort.MaxValue)
|
||||
{
|
||||
return Task.FromException(new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"校准速度 {speedValue} 超出范围(1~{ushort.MaxValue})"));
|
||||
}
|
||||
|
||||
return ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_calib_move(
|
||||
handle,
|
||||
distance,
|
||||
(ushort)speedValue),
|
||||
$"校准位移 {distance}mm",
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SaveCalibrationAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_calib_save, "保存校准参数", ct);
|
||||
|
||||
public Task TurnLaserOnAsync(byte frequency, CancellationToken ct = default) =>
|
||||
ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_laser_on(handle, frequency),
|
||||
$"激光器出光(频率 {frequency}Hz)",
|
||||
ct);
|
||||
|
||||
public Task TurnLaserOffAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_laser_off, "激光器关光", ct);
|
||||
|
||||
public Task SetLaserPowerAsync(byte power, CancellationToken ct = default) =>
|
||||
ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_laser_power(handle, power),
|
||||
$"设置激光能量 {power}",
|
||||
ct);
|
||||
|
||||
public Task StartSingleRangeAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_single_range, "单次测距", ct);
|
||||
|
||||
public Task StartContinuousRangeAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_continuous_range, "连续测距", ct);
|
||||
|
||||
public Task ControlLiftAsync(int position, CancellationToken ct = default)
|
||||
{
|
||||
var target = ToInt8(position, "升降位置");
|
||||
return ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_lift_control(handle, target),
|
||||
$"升降机构移动到 {target}",
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SetExternalTriggerAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_ext_trigger_set, "外部触发设置", ct);
|
||||
|
||||
public Task FireExternalTriggerAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_ext_trigger_fire, "外部触发出光", ct);
|
||||
|
||||
public Task StartAutoDescendAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_auto_descend, "自动下降检测", ct);
|
||||
|
||||
public Task StartFixedCycleAsync(
|
||||
ushort intervalMs,
|
||||
ushort count,
|
||||
CancellationToken ct = default) =>
|
||||
ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_fixed_cycle(handle, intervalMs, count),
|
||||
$"固定周期出光(周期 {intervalMs}ms,{count} 次)",
|
||||
ct);
|
||||
|
||||
public Task SetSyncTimeAsync(
|
||||
FocusSyncTime parameters,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
|
||||
var native = new Focus2SyncTimeParams
|
||||
{
|
||||
DelayUs = parameters.DelayUs,
|
||||
OffsetUs = parameters.OffsetUs,
|
||||
HoldUs = parameters.HoldUs,
|
||||
HoldOffsetUs = parameters.HoldOffsetUs,
|
||||
};
|
||||
|
||||
return ExecuteAsync(
|
||||
handle => FocusSystemNative.focus_sync_time_set(handle, ref native),
|
||||
"设置光谱仪同步延时",
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task RequestSyncTimeAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_sync_time_get, "获取光谱仪同步延时", ct);
|
||||
|
||||
public Task PowerOffAsync(CancellationToken ct = default) =>
|
||||
ExecuteAsync(FocusSystemNative.focus_power_off, "总电源关机", ct);
|
||||
|
||||
private async Task ExecuteAsync(
|
||||
Func<IntPtr, int> command,
|
||||
string operation,
|
||||
CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
// 命令内部会等待设备应答,放到线程池避免占用请求线程
|
||||
var result = await Task.Run(
|
||||
() => command(handle),
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
EnsureSuccess(handle, result, operation);
|
||||
_logger.LogInformation("对焦系统:{Operation}完成", operation);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 查询 ----------
|
||||
|
||||
public async Task<FocusSystemStatus> ReadSystemInfoAsync(
|
||||
int? timeoutMs = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
var timeout = NormalizeTimeout(timeoutMs);
|
||||
|
||||
return await Task.Run(
|
||||
() => ReadSystemInfoCore(handle, timeout, ct),
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private FocusSystemStatus ReadSystemInfoCore(
|
||||
IntPtr handle,
|
||||
int timeoutMs,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var deadline = Environment.TickCount64 + timeoutMs;
|
||||
var retryInterval = ResolveRetryInterval();
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = FocusSystemNative.focus_read_sys_info(handle, out var info);
|
||||
if (result == FocusSystemNative.Ok)
|
||||
{
|
||||
var status = MapStatus(info);
|
||||
|
||||
_logger.LogDebug(
|
||||
"对焦系统信息:位置={Position},错误={Error},激光在线={LaserOnline},电压={Voltage:F1}V",
|
||||
status.FocusPosition,
|
||||
status.Error,
|
||||
status.LaserOnline,
|
||||
status.VoltageVolts);
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
// 未收到应答/解析失败时在超时时间内重试,其余错误立即抛出
|
||||
if (result is not (FocusSystemNative.ErrTimeout
|
||||
or FocusSystemNative.ErrParseFailed))
|
||||
{
|
||||
throw MapNativeError(handle, result, "读取对焦系统信息");
|
||||
}
|
||||
|
||||
if (Environment.TickCount64 >= deadline)
|
||||
{
|
||||
var detail = result == FocusSystemNative.ErrTimeout
|
||||
? "未收到应答"
|
||||
: "CRC 校验失败或载荷不足";
|
||||
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.Timeout,
|
||||
$"读取对焦系统信息超时({timeoutMs}ms):{detail}");
|
||||
}
|
||||
|
||||
Thread.Sleep(retryInterval);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<FocusRealTimeResult> ReadResultAsync(
|
||||
int? timeoutMs = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var handle = RequireHandle();
|
||||
var timeout = NormalizeTimeout(timeoutMs);
|
||||
|
||||
return await Task.Run(
|
||||
() => ReadResultCore(handle, timeout, ct),
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private FocusRealTimeResult ReadResultCore(
|
||||
IntPtr handle,
|
||||
int timeoutMs,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var deadline = Environment.TickCount64 + timeoutMs;
|
||||
var retryInterval = ResolveRetryInterval();
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var result = FocusSystemNative.focus_query_result(handle, out var response);
|
||||
if (result == FocusSystemNative.Ok)
|
||||
{
|
||||
return MapResult(response);
|
||||
}
|
||||
|
||||
// 非阻塞查询,未找到结果帧时继续轮询
|
||||
if (result != FocusSystemNative.ErrTimeout)
|
||||
{
|
||||
throw MapNativeError(handle, result, "查询对焦系统结果");
|
||||
}
|
||||
|
||||
if (Environment.TickCount64 >= deadline)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.Timeout,
|
||||
$"查询对焦系统结果超时({timeoutMs}ms):未找到结果帧");
|
||||
}
|
||||
|
||||
Thread.Sleep(retryInterval);
|
||||
}
|
||||
}
|
||||
|
||||
private static FocusSystemStatus MapStatus(Focus2SysInfo info) =>
|
||||
new(
|
||||
info.FocusPos,
|
||||
info.Error,
|
||||
FocusSystemStatus.DescribeError(info.Error),
|
||||
info.Location,
|
||||
info.LaserSta != 0,
|
||||
info.Voltage / 10.0,
|
||||
info.ExtVoltage / 10.0,
|
||||
info.HwVersion,
|
||||
info.SwVersion,
|
||||
info.StartTime,
|
||||
info.SyncTime,
|
||||
info.SysSta != 0,
|
||||
DateTimeOffset.Now);
|
||||
|
||||
private static FocusRealTimeResult MapResult(Focus2RealTimeResp response)
|
||||
{
|
||||
var type = response.Type switch
|
||||
{
|
||||
0x01 => FocusRealTimeResultType.MessageAck,
|
||||
0x02 => FocusRealTimeResultType.RunningResult,
|
||||
0x03 => FocusRealTimeResultType.QueryResult,
|
||||
_ => FocusRealTimeResultType.Unknown,
|
||||
};
|
||||
|
||||
return new FocusRealTimeResult(
|
||||
type,
|
||||
response.Sta == 0x01,
|
||||
response.Error,
|
||||
type == FocusRealTimeResultType.QueryResult ? response.Data : null,
|
||||
DateTimeOffset.Now);
|
||||
}
|
||||
|
||||
// ---------- 参数校验与错误映射 ----------
|
||||
|
||||
private int NormalizeTimeout(int? timeoutMs)
|
||||
{
|
||||
var timeout = timeoutMs ?? _options.ReadTimeoutMs;
|
||||
return timeout > 0 ? timeout : 1000;
|
||||
}
|
||||
|
||||
private int ResolveRetryInterval() =>
|
||||
Math.Clamp(_options.ReadRetryIntervalMs, 10, 1000);
|
||||
|
||||
private static sbyte ToInt8(int value, string name)
|
||||
{
|
||||
if (value is < sbyte.MinValue or > sbyte.MaxValue)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"{name} {value} 超出范围({sbyte.MinValue}~{sbyte.MaxValue})");
|
||||
}
|
||||
|
||||
return (sbyte)value;
|
||||
}
|
||||
|
||||
/// <summary>命令返回 FOCUS2_OK(0) 表示成功,非 0 时按错误映射。</summary>
|
||||
private static void EnsureSuccess(IntPtr handle, int result, string operation)
|
||||
{
|
||||
if (result >= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw MapNativeError(handle, result, operation);
|
||||
}
|
||||
|
||||
private static HardwareException MapNativeError(
|
||||
IntPtr handle,
|
||||
int code,
|
||||
string operation)
|
||||
{
|
||||
var kind = code switch
|
||||
{
|
||||
FocusSystemNative.ErrNullPtr => HardwareErrorKind.InvalidArgument,
|
||||
FocusSystemNative.ErrBufTooSmall => HardwareErrorKind.InvalidArgument,
|
||||
FocusSystemNative.ErrFrameTooShort => HardwareErrorKind.CommunicationFailed,
|
||||
FocusSystemNative.ErrComOpenFailed => HardwareErrorKind.ConnectFailed,
|
||||
FocusSystemNative.ErrComNotOpen => HardwareErrorKind.NotConnected,
|
||||
FocusSystemNative.ErrComSendFailed => HardwareErrorKind.CommunicationFailed,
|
||||
FocusSystemNative.ErrParseFailed => HardwareErrorKind.CommunicationFailed,
|
||||
FocusSystemNative.ErrTimeout => HardwareErrorKind.Timeout,
|
||||
_ => HardwareErrorKind.Unknown,
|
||||
};
|
||||
|
||||
var hint = code switch
|
||||
{
|
||||
FocusSystemNative.ErrComOpenFailed => "(串口不存在或被占用)",
|
||||
FocusSystemNative.ErrComNotOpen => "(串口尚未打开)",
|
||||
FocusSystemNative.ErrComSendFailed => "(设备返回失败应答或串口发送失败)",
|
||||
FocusSystemNative.ErrParseFailed => "(CRC 校验失败或载荷不足)",
|
||||
FocusSystemNative.ErrTimeout => "(未收到应答)",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
var detail = FocusSystemNative.GetError(handle);
|
||||
var message = string.IsNullOrWhiteSpace(detail)
|
||||
? $"{operation}失败{hint}(错误码 {code})"
|
||||
: $"{operation}失败{hint}(错误码 {code}):{detail}";
|
||||
|
||||
return new HardwareException(kind, message);
|
||||
}
|
||||
|
||||
private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch
|
||||
{
|
||||
DllNotFoundException =>
|
||||
"加载 FocusSystem2.dll 失败:请确认该 DLL 已复制到程序输出目录"
|
||||
+ $"(当前目录:{AppContext.BaseDirectory})",
|
||||
BadImageFormatException =>
|
||||
"加载 FocusSystem2.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行",
|
||||
EntryPointNotFoundException =>
|
||||
"加载 FocusSystem2.dll 失败:DLL 版本与接口声明不匹配",
|
||||
_ => "加载 FocusSystem2.dll 失败",
|
||||
};
|
||||
|
||||
// ---------- 释放 ----------
|
||||
|
||||
private IntPtr RequireHandle()
|
||||
{
|
||||
var handle = _handle;
|
||||
if (!_connected || handle == IntPtr.Zero)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.NotConnected,
|
||||
"对焦系统尚未连接,请先调用连接接口");
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _gate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
CloseHandle();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
_gate.Dispose();
|
||||
}
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user