Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program wont close and aforge camera keeps running, threading trouble

I have a bit strange problem, which I find hard to debug Sometimes I can't close my program and it freezes when I try to close it.

I made a large program for video image recognition. I made a special button to close the camera. This button works with this by calling a function below, and it indeed, it does work.

 private void exitcamera()
 { 
 FinalVideo.SignalToStop();
 FinalVideo.WaitForStop();
 FinalVideo = null;
 }

Notice that the original video was started like this

 private void buttonStartCamera_Click(object sender, EventArgs e) 
 {
 FinalVideo = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);
 FinalVideo.DesiredFrameSize = new System.Drawing.Size(640, 480);
 FinalVideo.DesiredFrameRate = 90;
 FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
 FinalVideo.ProvideSnapshots = true;  //snapshots
 FinalVideo.Start(); 
 }

Now my problem seems (and this is a guess because I can't debug this moment) That some thread is still active wanting to update the main form with data. However it might not be able to do so since that one is closing. I think something like that is going on so I wrote on the main application form

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
     // Thread.Sleep(1000); // not sure about these delays might help syncing threads
     ExitCamera();
     Thread.Sleep(1000);
    }

However with that last code in place the program has even more trouble to exit.

I would like to send the subthreads an exit, but I dont know their names (if they have a name), I dont know how to list them or to instruct them to stop they are in another dll not my part of the code. From some dll's I dont have the code.

So are there ways of listing sub threads and then close them one by one, if one presses the uppercorner right cross to exit the application?

like image 700
user613326 Avatar asked Dec 08 '12 17:12

user613326


1 Answers

Well I managed to debug the program, and finally found what caused the problem. It is a little bit strange since as a button I could stop the camera using the exitcamera function.

However, inside a _formclosing event the same routine didn't work although it worked after I had marked out the waitforstop function.

 private void exitcamera()
 { 
  FinalVideo.SignalToStop();
  // FinalVideo.WaitForStop();  << marking out that one solved it
  FinalVideo.NewFrame -= new NewFrameEventHandler(FinalVideo_NewFrame); // as sugested
  FinalVideo = null;
 } 

I am still a bit confused about it, why this wont work in case a closing event. But it seems to be solved by this.

like image 191
user613326 Avatar answered Nov 15 '22 13:11

user613326