Is there any way to catch coroutine ending?

Hi, All !!

I started to connect openCV (this is C++ library) with unity3D and recently have known StartCoroutine function.
I thought that function is very useful and finally I implemented opencv call routine in the Coroutine.

code snippet is below

IEnumerator CameraRun() {
  initCamera(cameraWidth, cameraHeight);

  while(cameraRun) {
    queryNextFrame(cameraDataPtr, cameraWidth * cameraHeight * 3);
    yield return null;
    // do something job
  }

  releaseCamera();
}

void OnApplicationQuit() {
      cameraRun = false;
     // releaseCamera();
}

But, I could not reach to the point releaseCamera() function calling.
When OnApplicationQuit() function is called Coroutine stop suddenly and releaseCamera is never called.
So I have to call releaseCamera in OnApplicationQuit().

Why I want to call initCamera() and releaseCamera() in Coroutine is I think it is safe all function callings which have relation to web camera device is in same thread.

Anyway, Is there way to catch coroutine ending. I want to release camera in Coroutine ( I Always do this way in real Thread body function )

PS) I have whole code implementation but I can’t attatch file because of file size limitation

Another way to do something like this (title related) that someone might find useful would be to give a delegate in param of the IEnumerator

 using System;

 void call(){
     StartCoroutine(CameraRun(releaseCamera));
 }

 IEnumerator CameraRun(Action callback) {
   initCamera(cameraWidth, cameraHeight);

  (..yielding stuff..)
 
   if(callback != null) callback();
 }

void releaseCamera(){

}

You can use a boolean flag to know when the coroutine has finished. In the example below, the game will run until cameraRun becomes false: this will end the coroutine loop, execute releaseCamera() and set the variable cameraActive to false. The code in Update detects when cameraActive becomes false and calls Application.Quit(), ending the game:

// this boolean flag is true while the camera is active:
public bool cameraActive = true;

IEnumerator CameraRun() {
  initCamera(cameraWidth, cameraHeight);
  while(cameraRun) {
    queryNextFrame(cameraDataPtr, cameraWidth * cameraHeight * 3);
    yield return null;
    // do something job
  }
  releaseCamera();
  cameraActive = false;
}

void Update(){
  if (cameraActive == false){
    // camera deactivated: you can finish the application:
    Application.Quit();
  }
}

You can hijack the IEnumerator like this:

IEnumerator someCoroutine = aCoroutine();

Coroutine startSomeCoroutine = StartCoroutine(someCoroutine );

while (someCoroutine.MoveNext())
{
   Debug.Log("Im running");
   yield return null;
}
yield return startSomeCoroutine;

So when the loop is over, the routine is done.