Reputation: 538
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
and OnDiscCallback
are called from a C++ DLL. How do I structure the code so that the two functions are invoked in separate threads, in an asynchronous manner, without interrupting the for
loop?
Currently, the for
loop stops counting when either of the callbacks fire.
Upvotes: 0
Views: 2017
Reputation: 203
all you need to do is to update this line of code -
m.Connect(machineIndex, ptrConnect, ptrDisconnect);
to
System.Threading.Tasks.Task.Factory.StartNew(() => m.Connect(machineIndex, ptrConnect, ptrDisconnect));
This way, it starts your C++ code on a separate thread instead of on current running thread. Just make sure that you exit/dispose your C++ code cleanly before you exit your C# code.
Upvotes: 1