[英]Bitmap - ArgumentException: “Parameter is not valid.” (intermittent)
I am doing simple library to work with my webcam (using Aforge.net). 我正在做一个简单的库来使用我的网络摄像头(使用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);
我的问题是,我有时会收到
ArgumentException was Unhandled
此行中的Parameter was Invalid
, return new Bitmap(img);
But img
at the time of exception seems OK, simple bitmap 640x480 (not so big). 但是异常时的
img
似乎还可以,简单的位图为640x480(不是很大)。 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. 我一直在网上搜索,发现这可能是一些内存问题(我是针对32位的),但是发生这种情况时,我的整个过程不会超过150MB。
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 lock
不是问题-没有lock
也会发生 img
in not null
img
中的值不为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.Dispose()
Thread.Sleep()
之后img.Dispose()
puttin Thread.Sleep()
我也得到了这个ArgumentException,但是这次我真的可以在监视列表中看到所有img
参数都是无效的... 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. img
似乎一切就OK了...只有我可以在那一刻想到的事情是,我打电话img
的时候,它以其他线程处理。 But I do not know how to prevent this. Sometimes the debugger can be wrong (even if it is unlikely). 有时调试器可能是错误的(即使不太可能)。 Have you tried addind a null-check just to be cautious ?
为了谨慎起见,您是否尝试过addind空检查?
// 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.
我敢打赌,在您调用MakePicture()方法时,您的img对象已锁定。 You could try reproducing this byt adding a thread.Sleep() inside your lock.
您可以尝试通过在锁内添加thread.Sleep()来重现此错误。 If the problem actually comes from the lock, you may want to use a different pattern.
如果问题实际上出在锁上,则可能要使用其他模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.