using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TeamAAS_VP.Helpers
{
///
/// VisionPro 工具辅助类。
/// 提供在独立 STA 线程中异步执行 CogToolBlock 的能力,
/// 避免 COM 封送到主 UI 线程导致界面假死。
///
public static class VisionProHelper
{
///
/// 在专用 STA 后台线程中异步运行 ToolBlock。
/// 每次调用创建一个新的 STA 线程,ToolBlock 执行完毕后线程自动退出。
///
/// 要执行的 CogToolBlock 实例
/// 异步任务,完成时表示 ToolBlock 执行完毕
public static Task RunToolBlockAsync(CogToolBlock toolBlock)
{
if (toolBlock == null)
throw new ArgumentNullException(nameof(toolBlock));
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
try
{
toolBlock.Run();
tcs.TrySetResult(true);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
})
{
IsBackground = true,
Name = $"VP-Run-{Guid.NewGuid():N}"
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
///
/// 在专用 STA 后台线程中异步加载 VisionPro 序列化对象(.vpp 文件等)。
///
/// 反序列化的目标类型
/// .vpp 文件完整路径
/// 包含反序列化对象的异步任务
public static Task LoadVisionProObjectAsync(string filePath) where T : class
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
try
{
var obj = CogSerializer.LoadObjectFromFile(filePath) as T;
tcs.TrySetResult(obj);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
})
{
IsBackground = true,
Name = $"VP-Load-{Guid.NewGuid():N}"
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
///
/// 在专用 STA 后台线程中异步保存 VisionPro 对象到文件。
///
/// 要保存的对象
/// 目标文件路径
/// 异步任务
public static Task SaveVisionProObjectAsync(object obj, string filePath)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException(nameof(filePath));
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
try
{
CogSerializer.SaveObjectToFile(obj, filePath);
tcs.TrySetResult(true);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
})
{
IsBackground = true,
Name = $"VP-Save-{Guid.NewGuid():N}"
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
}
}