带有多线程的C#System.Reflection.TargetInvocationException

时间:2017-06-28 14:01:52

标签: c# multithreading devexpress tcplistener gridcontrol

我使用Devexpress GridControl。我想根据tcp消息更改单元格值。

private void Form1_Load(object sender, EventArgs e)
{
        grid_mygrid.DataSource = Get_Devices_Info.Get_Device_From_DB().Tables[0];
        this.tcpListener = new TcpListener(IPAddress.Any, 2000);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Priority = ThreadPriority.Highest;
                this.listenThread.Start();
}
private void ListenForClients()
        {
            this.tcpListener.Start();
            while (true)
            {
                TcpClient client = this.tcpListener.AcceptTcpClient();
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }

private void HandleClientComm(object client)
        {
        ...
        try
          {
            gridView1.SetRowCellValue(row_index, "boot_progress", 50);
          }
        catch(Exception e)
          {
            if (e.InnerException != null)
               {                                            
                  Log2LogText(e.InnerException.Message);
               }
           }            
        ...
    }

如果我想在线程

下尝试这个
gridView1.SetRowCellValue(row_index, "boot_progress", 50);

如果row_index = 0 - >没关系 如果row_index> 0 - > 未处理的类型' System.Reflection.TargetInvocationException'发生在mscorlib.dll

关于GridControl 如果我点击按钮尝试这个

gridView1.SetRowCellValue(1, "boot_progress", 50); -> It is OK
gridView1.SetRowCellValue(2, "boot_progress", 50); -> It is OK
gridView1.SetRowCellValue(4, "boot_progress", 50); -> There is no row with index 4. But there is no error. It is OK.
gridView1.SetRowCellValue(5, "random_column", 50); -> There is no column with "random_column". But there is no error. It is OK.

我使用try-catch但是这段代码仍然会出错并且程序停止。当我评论这一行时

gridView1.SetRowCellValue(row_index, "boot_progress", 50);

没有问题

我在等你的建议。

1 个答案:

答案 0 :(得分:0)

根据SLaks的建议,我从我的TCP中分离出我的UI代码。例如,读这个 Updating a Grid datasource from a separate thread