2016-02-17 1 views
0
class Program 
{ 
    [UnmanagedFunctionPointer(CallingConvention.StdCall)] 
    delegate int delConnectionCallback(IntPtr caller, int MachineIndex); 

    [UnmanagedFunctionPointer(CallingConvention.StdCall)] 
    delegate int delDisconnectionCallback(IntPtr caller, int MachineIndex)); 

    static void Main(string[] args) 
    { 
    // 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); 

    for (long i = 0; i < 9999999999999; i++) 
    { 
     Console.WriteLine(i); 
    } 

    Console.Read(); 
    } 

    // 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 et OnDiscCallback sont appelés à partir d'une DLL C++. Comment structurer le code afin que les deux fonctions soient invoquées dans des threads séparés, de manière asynchrone, sans interrompre la boucle for?C# - Comment avoir une fonction de rappel invoquée dans un thread séparé

Actuellement, la boucle for arrête de compter lorsque l'un des rappels se déclenche.

+0

Comment votre dll C++ est-elle au courant? – nvoigt

+0

Mise à jour du code. Voir au dessus. – RaduTomy

+0

J'ai édité votre question mais je pense que c'est encore vague. Voulez-vous que les callbacks soient invoqués dans un thread séparé afin que la boucle 'for' ne soit pas interrompue? Si oui, ma modification reflète cela. (PS: Veuillez attendre que l'édition soit approuvée.) – Sabuncu

Répondre

1

tout ce que vous devez faire est de mettre à jour cette ligne de code -

m.Connect(machineIndex, ptrConnect, ptrDisconnect); 

à

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

De cette façon, il commence votre code C++ sur un thread séparé au lieu du fil conducteur en cours . Assurez-vous simplement de quitter/éliminer votre code C++ proprement avant de quitter votre code C#.