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

时间:2016-02-17 17:11:40

标签: c# multithreading callback delegates invoke

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;
  };
}
从p + DLL调用

OnConnCallbackOnDiscCallback。如何构造代码,以便以异步方式在不同的线程中调用这两个函数,而不会中断for循环?

目前,for循环会在任何一个回调触发时停止计数。

1 个答案:

答案 0 :(得分:1)

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

m.Connect(machineIndex, ptrConnect, ptrDisconnect);

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

这样,它就可以在单独的线程上启动C ++代码,而不是在当前运行的线程上启动。只需确保在退出C#代码之前彻底退出/处理C ++代码。