【问题标题】:Callback function invoked in a separate thread在单独的线程中调用的回调函数
【发布时间】:2016-02-17 17:11:40
【问题描述】:
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 循环会在任一回调触发时停止计数。

【问题讨论】:

  • 你的 C++ dll 是如何知道这些的?
  • 更新了代码。见上文。
  • 我已经编辑了您的问题,但我觉得它仍然含糊不清。您是否希望在单独的线程中调用回调以便for 循环不被中断?如果是这样,我的编辑反映了这一点。 (PS:请等待修改通过。)
  • @Sabuncu 是的,完全正确。

标签: c# multithreading callback delegates invoke


【解决方案1】:

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

m.Connect(machineIndex, ptrConnect, ptrDisconnect);

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2021-07-23
    • 2013-12-05
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多