我的应用程序中有条形码扫描功能。主页面上有一个条形码按钮,用户点击该按钮后进入条形码扫描页面。但当它导航回来时,我收到一个消息框,上面写着:
This instance has been disposed. Possibly because another component required a shared resource.
我处理了PhotoCamera
,并取消了条形码扫描页面上OnNavigatedFrom
方法中的所有事件,但仍然得到了相同的结果。
我进入代码,发现这个方法有问题:
PhotoCamera _cam;
VideoBrush _videoBrush = new VideoBrush();
Stopwatch watch = new Stopwatch();
int _nbTry;
Result result = null;
void cam_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
{
if (result == null)
{
try
{
_nbTry++;
watch.Reset();
watch.Start();
while ((result == null) && (watch.ElapsedMilliseconds < 1500) && _cam != null)
{
var binaryBitmap = GetBitmapFromVideo(_cam);
if (binaryBitmap != null)
{
try
{
result = BarCodeManager.ZXingReader.decode(binaryBitmap);
}
catch
{
// Wasn't able to find a barcode
}
}
}
if (result != null)
{
BarCodeManager._onBarCodeFound(result.Text);
}
else
{
if (_cam != null)
{
_cam.Focus();
}
}
}
catch (Exception exc)
{
BarCodeManager._onError(exc);
}
}
}
有一个异常被捕获,下面是堆栈跟踪:
at Microsoft.Devices.Camera.InvokeAndRemapExceptions(Action a)
at Microsoft.Devices.PhotoCamera.get_IsFocusSupported()
at Microsoft.Devices.PhotoCamera.Focus()
at WP7.ScanBarCode.BarCode.cam_AutoFocusCompleted(Object sender, CameraOperationCompletedEventArgs e)
at Microsoft.Devices.Camera.<>c__DisplayClass21`1.<SafeFireEvent>b__1f(Object ignored)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
有什么想法吗?谢谢
第一次离开条形码扫描页面时,您可能会处理PhotoCamera
。
如果你只是处理PhotoCamera
对象,当你返回条形码扫描页面时,你会得到这个错误:
This instance has been disposed. Possibly because another component required a shared resource.
尝试处理PhotoCamera
对象以及所有事件委托,如Initialized
或相关:
// Release the camera object:
PhotoCamera.Dispose();
// Remove initialization event:
PhotoCamera.Initialized -= PhotoCamera_Initialized;
// For example, you must remove also the events linked to the camera management (e.g. when you press camera buttons):
CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
当您进入条形码扫描页面的OnNavigatedFrom
事件时,调用此处置代码,一切都应该正常!