各位程序员,大家好!
我正在为具有条形码阅读器硬件的Windows Mobile6.1设备开发Windows Forms .NET Compact Framework2.0。
我可以使用条形码阅读器读取条形码,也可以激活和停用条形码。除了当我试图读取一些东西并转到下一个表单时,我得到了一个objectdisposedexception。发生这种情况(我猜)是因为我必须处理条形码阅读器的实例,然后在下一个表单中创建一个新的实例。
问题是:当我使用按钮转到下一个表单,使用相同的代码来处理条形码读取器时,我没有objectdisposedexception异常。当我简单地将表单加载放在textchanged事件上时,错误会上升,但不会被任何try/catch语句捕获,从而导致应用程序崩溃。
我也不能调试它,因为windows mobile的VS模拟器不能和设备的barcodereader DLL一起工作。
有人能帮我吗?
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
//DLL that controls the barcodereader
using Intermec.DataCollection;
namespace WOPT_Coletor.view.ConsultarPosicao
{
public partial class frmConsultarPosicao_2 : Form
{
public BarcodeReader leitor;
public frmConsultarPosicao_2()
{
InitializeComponent();
ShowHide.ShowTopStatusbar(false);
//code to work with the barcode reader
model.LeitorCodigoDeBarras classeLeitor = new model.LeitorCodigoDeBarras();
leitor = classeLeitor.LerCodigoDeBarras();
leitor.BarcodeRead += new BarcodeReadEventHandler(this.eventoLeitorCodigoDeBarrasArmazenagem1);
}
//Event to receive the barcode reading information
void eventoLeitorCodigoDeBarrasArmazenagem1(object sender, BarcodeReadEventArgs e)
{
tbCodMaterial.Text = e.strDataBuffer.Trim();
}
private void tbCodMaterial_TextChanged(object sender, EventArgs e)
{
try
{
if (tbCodMaterial.Text.Length == 23)
{
Cursor.Current = Cursors.WaitCursor;
Cursor.Show();
//disposal of the barcodereader instance
leitor.ScannerOn = false;
leitor.ScannerEnable = false;
leitor.Dispose();
leitor = ((BarcodeReader)null);
//processing of the information read.
char[] auxcodMaterial = new char[9];
using (StringReader str = new StringReader(tbCodMaterial.Text))
{
str.Read(auxcodMaterial, 0, 8);
}
string codMaterial = new string(auxcodMaterial);
//loads next form
Form destino = new frmConsultarPosicao_3(codMaterial);
destino.Show();
Cursor.Current = Cursors.Default;
Cursor.Show();
//closes and dispose of the current form
this.Close();
this.Dispose(true);
}
}
catch (ObjectDisposedException ex)
{
MessageBox.Show(ex.Message);
}
}
}发布于 2013-03-01 01:56:11
在不了解条形码阅读器的应用程序接口和行为的情况下,我猜测这是一个竞争条件,当您在tbCodMaterial_TextChanged中时,您的BarCodeRead事件可能会触发。我建议在禁用扫描器的代码周围放置一个同步块,并且只在扫描器为非空的情况下在该块内执行关闭:
private readonly Object mySynchronizationObject = new Object;
...
lock (mySynchronizationObject)
{
if (leitor != null)
{
//disposal of the barcodereader instance
...
}
}在关机之前断开与事件的连接也不会有什么坏处(在上面的锁中):
leitor.BarcodeRead -= new BarcodeReadEventHandler(this.eventoLeitorCodigoDeBarrasArmazenagem1);https://stackoverflow.com/questions/15141407
复制相似问题