Search code examples
c#c++pinvokebreakterminate

How to Terminate a C++ Function Called form C# Using p/invoke


I am calling a C++ function from C# using p/invoke, this function has an infinite loop (capturing frames to a file) which should be broken when an event is happened in C#.

How can I break that loop (which terminates that function)?

I tried to run this function in a thread in C#, and abort that thread when termination is needed. But the abort function didn't work.

Thread thread = new Thread(myMethod);
thread.Start();

// to terminate the function
thread.Abort();     //didn't respond

Solution

  • Probably the safest way is to do two things:

    1. Expose another function named (eg) StopRecording that sets a global variable inside your native code
    2. Inside your main function, check the value of the global at the start of every loop iteration to see if StopRecording has been called (and if so, break out of the loop)

    This lets it terminate naturally without requiring any heavy-handed terminations.