I am doing simple library to work with my webcam (using Aforge.net). At the moment I am creating method to get a single picture from the camera. Here is sample of my code:
private Bitmap img = new Bitmap(10,10);
// start camera
public void StartCam( int ind)
{
cam = new VideoCaptureDevice(videoDevices[ind].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
// new frame event
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
lock (img)
{
if (img != null)
img.Dispose();
img = (Bitmap)eventArgs.Frame.Clone();
}
}
// return picture method
public Bitmap MakePicture()
{
return new Bitmap(img);
}
My issue is that from time to time I get ArgumentException was Unhandled - Parameter was Invalid in this row return new Bitmap(img);
But img at the time of exception seems OK, simple bitmap 640x480 (not so big). I have been searching on the net and found it could be some memory issue (I do it for 32bit) but my whole process does not exceed 150MB when this happens.
Do you know what could cause this and how to avoid this?
Thanks for your help!
EDIT:
lockis not an issue - it happens also without itimgin notnull- puttin
Thread.Sleep()afterimg.Dispose()I get also this ArgumentException, but this time I can really see in Watch List that allimgparameteres are invalid... - when this happens with the code I have here, ArgumentException: “Parameter is not valid.” is raised but looking at
imgthere seems everything OK... Only thing I can think of at the moment is that I am callingimgat time when it is disposed of in other thread. But I do not know how to prevent this.