【问题标题】:Strange behaviour using rows.insert on a seprate thread在单独的线程上使用 rows.insert 的奇怪行为
【发布时间】:2014-02-16 00:07:25
【问题描述】:

我在 vb.net 中创建了一个简单的 WinForm 应用程序,它读取 csv 文件并在 DataGridView 组件中显示其内容。下面是我在主 ui 线程上运行的代码。

For Each line In fileinput
  Dim elements = line.Split(",")
  DataGridView1.rows.insert(0,elements)
Next

上面的代码在主窗体线程上运行良好。元素数组用于填充每行中的所有单元格,但如果我在单独的线程上尝试相同的代码,我在每行的第一个单元格中得到的只是 System.String []。有人知道为什么会这样吗?

这是在新线程上创建和运行的完整代码:

Dim Filename As String = ""

Private Sub BtnCsv_Click(sender As Object, e As EventArgs) Handles BtnCsv.Click

    Opf.ShowDialog()
    Filename = Opf.FileName

    Dim t As Thread
    t = New Thread(AddressOf Me.ParseFileThread)
    t.Start()



End Sub

Public Sub ParseFileThread()

    'RtfOut.Text = Filename

    'Read All Lines From The File since Its a csv
    Dim inputFile() = File.ReadAllLines(Filename)
    'The first line contains the headers for the csv file
    Dim headers() = inputFile(0).Split(",")

    SetGridHeaders(headers)
    SetDataGrid(inputFile)

End Sub

Public Delegate Sub SetGridHeadersDelegate(ByVal headers As Array)

Public Sub SetGridHeaders(ByVal headers As Array)
    If Dgv.InvokeRequired Then
        Dgv.BeginInvoke(New SetGridHeadersDelegate(AddressOf SetGridHeaders), headers)
    Else
        For Each header In headers
            Dgv.Columns.Add(header, header)
            Dgv.Refresh()
        Next
    End If
End Sub

Public Delegate Sub SetDataGridDelegate(ByVal values As Array)

Public Sub SetDataGrid(ByVal values As Array)
    If Dgv.InvokeRequired Then
        Dgv.BeginInvoke(New SetDataGridDelegate(AddressOf SetDataGrid), values)
    Else
        For Each line In values
            Dim cells = line.Split(",")
            Dgv.Rows.Insert(0, cells)
            Dgv.Refresh()
        Next
    End If
End Sub

【问题讨论】:

    标签: vb.net multithreading winforms datagridview


    【解决方案1】:

    试试这个:

    Me.Invoke(Sub()
              DataGridView1.Rows.Insert(0, elements)
              End Sub)
    

    当您更改活动 UI 线程上的控件时,更改需要在该线程本身内部发生,否则您会遇到问题。我很惊讶代码执行时没有引发异常。

    Me.Invoke 将确保在主线程中填充数据。

    【讨论】:

    • 我已经试过了。这就是我首先得到奇怪行为的方式。不过感谢您的回复。
    • 好的,我收回。我删除了我自己的线程代码并使用了你的代码,它运行良好。非常感谢!
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2018-09-30
    相关资源
    最近更新 更多