0

我收到这个错误..

我正在尝试使用超过 1000 条记录处理数据库插入方法的进度条。我需要进度条在线程中加载完全相同的进程..

我得到了错误;跨线程操作无效;控件'listview1' 从创建它的线程以外的线程访问。

    Imports System.IO
Public Class Form1
    Private WithEvents DT As New DataTable
    Private Delegate Sub AsyncDelegate(ByVal value As Integer)
    Private ProgressUpdater As New AsyncDelegate(AddressOf UpdateProgress)
    Private DataLoader As AsyncDelegate
    Private DataLoaderIAsync As IAsyncResult
    Private UpdateIncrement As Integer

    Private Sub LoadListAttendance()
        Dim txtLine As String = ""
        ListView1.Items.Clear()
        If File.Exists(strFileNameAndPath) = True Then
            Dim objReader As New StreamReader(strFileNameAndPath)

            Do While objReader.Peek() <> -1
                Dim strLine As String = objReader.ReadLine()
                If Split(strLine, " ")(0) = "" Then MessageBox.Show("Invalid file.", SysMsg, MessageBoxButtons.OK) : Exit Sub
                ListView1.Items.Add(Split(strLine, " ")(0))
                ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(Mid(Split(strLine, " ")(1), 1, 8))
                ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(Mid(Split(strLine, " ")(1), 9, 4))
                ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(Mid(Split(strLine, " ")(1), 13, 2))
            Loop
        End If
    End Sub


    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        'Initialize the progress bar.

        'Run a scalar command to select the row count and set the progress maximum

        'Calculate a percentage for the Row Changed event.
        '  ie if total recs is 1,000,000 set the progress amount to 10% of that.
        '  *See DT_RowChanged

        UpdateIncrement = 100000

        'DeEnable any controls you may not want the user to touch until the 
        'load is complete.

        'Load the data Ascync
        DataLoader = New AsyncDelegate(AddressOf LoadData)
        DataLoaderIAsync = DataLoader.BeginInvoke(0, New AsyncCallback(AddressOf LoadData_Completed), Nothing)


    End Sub





    Private Sub LoadData()

        'Your Load data code.
        'This sample code loads 1,000,000 recs

        'Do not access any controls in the procedure
        If Not checkServer() = True Then frmServerSet.ShowDialog()
        For x As Integer = 0 To ListView1.Items.Count - 1
            'If RecExist_2("tbltxt", "date", ListView1.Items(x).SubItems(1).Text, "id", ListView1.Items(x).Text, False) = False Then
            sqlSTR = "insert into tbltxt (id,date,time,code) values"
            sqlSTR = sqlSTR & " ( '" & ListView1.Items(x).Text & "','" & ListView1.Items(x).SubItems(1).Text & "','" & ListView1.Items(x).SubItems(2).Text & "', '" & ListView1.Items(x).SubItems(3).Text & "')" ','" & t1 & "')"

            ExecuteSQLQuery(sqlSTR)

            'End If
        Next
        MsgBox("ok")
    End Sub

    Private Sub LoadData_Completed()

        'Async op has completed.
        'Call the endinvoke to the delegate and unlock the UI

        'Do not access any controls in this procedure

        DataLoader.EndInvoke(DataLoaderIAsync)

        Me.Invoke(New AsyncDelegate(AddressOf UnlockUI), New Object() {Nothing})

    End Sub

    Private Sub UnlockUI()
        'Do what you want to the UI Here.
        ProgressBar1.Visible = False

    End Sub

    Private Sub UpdateProgress(ByVal value As Integer)
        'Updates the progress bar from the thread it was
        'created on.
        If ProgressBar1.InvokeRequired Then
            ProgressBar1.Invoke(ProgressUpdater, New Object() {value})
        Else
            If value > ProgressBar1.Maximum Then value = ProgressBar1.Maximum
            ProgressBar1.Value = value
        End If

    End Sub

    Private Sub DT_RowChanged(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) Handles DT.RowChanged
        'Handle a row change
        'Do not access any controls from this procedure

        Static counter As Integer = 1

        'first make sure the row is being added
        If e.Action = DataRowAction.Add Then
            'next check for an increment.  In this case I have a hard coded
            '100,000 Which is 10% of the million records that I know I have.

            'Do not update the progress bar on every record

            If counter Mod UpdateIncrement = 0 Then
                UpdateProgress(counter)
            End If
            counter += 1
        End If

    End Sub
End Class
4

1 回答 1

2

LoadData 在后台线程上运行;您无法从此线程中与列表视图(甚至读取值)交谈。更常见。您将在 UI 线程上从 UI构建一些模型(我将有一些自定义类的列表,将每个值表示为属性),然后使该模型可用于工作线程。然后在后台线程中,您只能访问与 UI 无关的模型。

另外:不要连接值来生成 SQL。那就是自杀——这是一个明显的 SQL 注入风险。请改用无参数查询,或为您处理参数化的工具。

于 2012-09-15T08:05:07.040 回答