【发布时间】: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;
};
}
OnConnCallback 和 OnDiscCallback 从 C++ DLL 调用。如何构造代码,以便在单独的线程中以异步方式调用这两个函数,而不会中断for 循环?
目前,for 循环会在任一回调触发时停止计数。
【问题讨论】:
-
你的 C++ dll 是如何知道这些的?
-
更新了代码。见上文。
-
我已经编辑了您的问题,但我觉得它仍然含糊不清。您是否希望在单独的线程中调用回调以便
for循环不被中断?如果是这样,我的编辑反映了这一点。 (PS:请等待修改通过。) -
@Sabuncu 是的,完全正确。
标签: c# multithreading callback delegates invoke