I am using this PictureBox on a form, to this picture box I use the AForge Code. I pass the REFERENCE of the pictureBox into a webcam class I create that initializes the webcam and tells it where to draw its frames to....so it happily draws it frames... no problemo.
But then certain times (when I want to do stuff with said image, if a chck box is clicked)...I start this timer using simple code:
timer1.Enabled = true;
this timer's interval is set to 33.
So now its firing along and every time through the loop my code has this:
private void timer1_Tick(object sender, EventArgs e)
{
...
double value = detector.ProcessFrame(new Bitmap(picCapture.Image)); //errors here
...
TimerCallback tc = new TimerCallback(sendDataFast);
System.Threading.Timer t = new System.Threading.Timer(tc, null, 2000, Timeout.Infinite);
}
That line above has one of three errors I have seen on it (Stack traces where available):
Object is currently in use elsewhere.
Out of Memory.
(A first chance exception of type 'System.OutOfMemoryException' occurred in System.Drawing.dll)
Parameter not valid
(A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll)
I am certain these are threading issues but I have no clue how to deal with them...I am totally lost. If the program hangs on that line above, I can usually click run again in the debugger and all is well. But I don't want to be sloppy and just put in a willy nilly try catch that continues. I would like to figure out the root of this issue..
I saw somewhere else someone said it could be a threading issue and to put this line: System.Diagnostics.Debug.Assert(!this.InvokeRequired, "InvokeRequired");
So I did at the top of that time1_click method but the assert doesn't seem to be happening, but i am not sure this was the right place for the assert... is timer1_click in a UI thread or not?
I suspect now that I reviewed my code its something with the way I initialize my webcam class:
Or within that timer1_click I also make a call to this method:
void sendDataFast(Object stateObject)
{
EmergencyDelegate delEmergency =
new EmergencyDelegate(mic.sendDataEmergency);
// call the BeginInvoke function! //sendDataEmergency takes in a picture Image picImage as an argument.
delEmergency.BeginInvoke(picCapture.Image, null, null);
}
And for completeness this is how I initialize my webcam class:
webcam = new WebCam();
webcam.InitializeWebCam(ref picCapture, ref picComparator, ref dataObject, this); //guessing this is calling threading issues
Those three errors that happen don't happen right away, seems to happen randomly one of the three.... leads me to think its a threading issue but how else can I fix this? creating a delegate for some reason that returns that double value and is called if invoke required is true?