0

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 it
  • img in not null
  • puttin 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...
  • when this happens with the code I have here, ArgumentException: “Parameter is not valid.” is raised but looking at 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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, I have done some more testing, but I must admit I am kind of lost now because nothing helped much. What different pattern do you mean? Now I think of making the img public, but this issue could happen anywhere else...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.