使用线程插入数据时出错引发异常

时间:2015-07-27 05:22:13

标签: c# multithreading winforms exception unhandled-exception

我在winform中使用线程时有probem。 我在调试程序时遇到错误。

我的应用程序在启动程序时抛出异常。

My Application throw exception when start program

我定义class RunInUIThread是:

private void RunInUIThread(Delegate method)
{
    this.BeginInvoke(method);
}

在RunInUIThread方法中,如:

BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
          BaiXeDTO obj = new BaiXeDTO();      //Map all to define database 
          txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
          txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();

          //If I comment all below code. It's work. But I need Insert data to database.
          txtKhuVucBai.Text = obj.IDBaiXe.ToString();
          txtMaThe.Text = obj.IDRF.ToString();
          obj.BienSoXe = textBox1.Text;
          obj.HinhBienSo = color.ToString();
          obj.HinhChuXe = img.ToString();
          obj.ThoiGianVao = DateTime.Now.ToLocalTime();
          obj.ThoiGianRa = DateTime.Now.ToLocalTime();
          baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));

为什么我的代码不起作用。有人可以解释我以及如何解决问题? 感谢所有读者!!!

2 个答案:

答案 0 :(得分:0)

@JoelLegaspiEnriquez,您建议我删除Program.cs中的[STAThread]吗?

如果我评论这一行。这在控制方面存在问题AxLiveX1是对摄像机ip的控制。

Exception Error when debug

txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();是16字节的Guid类型:8d58d690-6b71-4ee8-85ad-006db0287bf1。

但我将txtKhuVucBai分配给Guid类型是:

private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
        get { return mCurrentCardIDBlock1; }
}

mCurrentCardIDBlock1是具有32个字符随机的RFID阅读器类型。

答案 1 :(得分:0)

我的意思是尝试在没有ThreadStart

的情况下运行此代码块
{
    BaiXeDTO obj = new BaiXeDTO();      //Map all to define database 
    txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
    txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();

    //If I comment all below code. It's work. But I need Insert data to database.
    txtKhuVucBai.Text = obj.IDBaiXe.ToString();
    txtMaThe.Text = obj.IDRF.ToString();
    obj.BienSoXe = textBox1.Text;
    obj.HinhBienSo = color.ToString();
    obj.HinhChuXe = img.ToString();
    obj.ThoiGianVao = DateTime.Now.ToLocalTime();
    obj.ThoiGianRa = DateTime.Now.ToLocalTime();
    baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}

这是在主线程中调试代码。