Reputation: 48
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:
lock
is not an issue - it happens also without itimg
in not null
Thread.Sleep()
after img.Dispose()
I get also this ArgumentException, but this time I can really see in Watch List that all img
parameteres are invalid...img
there seems everything OK... Only thing I can think of at the moment is that I am calling img
at time when it is disposed of in other thread. But I do not know how to prevent this.Upvotes: 0
Views: 1127
Reputation: 94
Sometimes the debugger can be wrong (even if it is unlikely). Have you tried addind a null-check just to be cautious ?
// return picture method
public Bitmap MakePicture()
{
Bitmap res = null;
if (img != null)
res = new Bitmap(img);
return res;
}
But I don't think that is the problem. I would bet your img object is locked at the time you're calling your MakePicture() method. You could try reproducing this byt adding a thread.Sleep() inside your lock. If the problem actually comes from the lock, you may want to use a different pattern.
Upvotes: 1