在单独的线程中调用的回调函数

本文关键字:回调 函数 调用 线程 单独 | 更新日期: 2023-09-27 18:34:58

class Machine
{
  [UnmanagedFunctionPointer(CallingConvention.StdCall)]
  delegate int delConnectionCallback(IntPtr caller, int MachineIndex);
  [UnmanagedFunctionPointer(CallingConvention.StdCall)]
  delegate int delDisconnectionCallback(IntPtr caller, int MachineIndex));
  private static void Run()
  {
     // random machine for test purposes
     int machineIndex = 12;
     // Return the memory address of the functions where the callback will happen
     // These will be passed to the MachineDriverDLL class so that the C++ Driver DLL 
     //    knows where to return the call
     IntPtr ptrConnect = Marshal.GetFunctionPointerForDelegate(OnConnCallback);
     IntPtr ptrDisconn = Marshal.GetFunctionPointerForDelegate(OnDiscCallback);
     // map the machine dll object 
     var m = new MachineDriverDll();
     // connect to the machine
     m.Connect(machineIndex, ptrConnect, ptrDisconnect);
  }
  // Connect call from the DLL driver
  private static delConnectionCallback OnConnCallback = (caller, MachineIndex) =>
  {         
     Log(MachineIndex);
     // more long code here
     return 0;
  };
  // Disconnect Call from the DLL driver
  private static delDisconnectionCallback OnDiscCallback = (caller, MachineIndex) =>
  {
     Log(MachineIndex);
     // more long code here
     return 0;
  };
}

OnConnCallbackOnDiscCallback是从C++ DLL 调用的。如何构建代码,以便在单独的线程中以异步方式调用这两个函数,而不会中断for循环?

目前,当任一回调触发时,for循环将停止计数。

在单独的线程中调用的回调函数

您需要做的就是更新这行代码 -

m.Connect(machineIndex, ptrConnect, ptrDisconnect);

System.Threading.Tasks.Task.Factory.StartNew(() => m.Connect(machineIndex, ptrConnect, ptrDisconnect));

这样,它会在单独的线程上启动C++代码,而不是在当前正在运行的线程上启动。只需确保在退出 C# 代码之前干净地退出/释放C++代码即可。