首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程间操作无效;从我在进度栏中使用的线程以外的线程访问了控件“”listview1“”

线程间操作无效;从我在进度栏中使用的线程以外的线程访问了控件“”listview1“”
EN

Stack Overflow用户
提问于 2012-09-15 15:51:06
回答 1查看 1.3K关注 0票数 0

我得到了这个错误..

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

我在以下位置得到错误:交叉线程操作无效;从创建控件'listview1‘的线程以外的线程访问该控件。

代码语言:javascript
复制
    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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-15 16:05:07

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12435591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档