Hello其他程序员!
我正在为具有条形码阅读器硬件的Windows Mobile 6.1设备开发Windows Forms .NET Compact Framework 2.0。
我可以使用条形码阅读器读取条形码,我也可以激活和停用条形码。 除了当我尝试阅读某些内容并转到下一个表单时,我得到一个objectdisposedexception。这种情况发生(我猜)因为我必须处理条形码阅读器的实例,然后在下一个表单中创建一个新的条形码阅读器。
问题是:当我使用按钮转到下一个表单时,使用相同的代码来处理条形码阅读器我没有objectdisposedexception。当我简单地将表单加载到textchanged事件上时,错误会上升,但不会被任何try / catch语句捕获,从而导致应用程序崩溃。
我也无法调试它,因为Windows移动设备的VS模拟器不能与设备条形码读取器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);
}
}
}
答案 0 :(得分:1)
在不了解条形码阅读器的API和行为的情况下,我猜你有一个竞争条件,当你进入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);