多任务覆盖变量

Multi task overriding variables

首先抱歉我的英语不好!

那么现在,我的问题是:我有一个过程需要 运行 快速 - 它有大量数据,我想 运行 以 multithread/multitask 的方式 - (我不知道这样做是不是最好的方法)

我有两个subs(),如下:

 Sub read_file_do_something_and_insert_table()
        Dim t As Task
        Dim FULLPATH As String = ""
        Dim i As Integer = 0
        Dim arr() As String
        Try
            Using oReader As StreamReader = New StreamReader(FULLPATH)
                While Not oReader.EndOfStream
                    Try
                        i = i + 1
                        arr = oReader.ReadLine.Split(vbTab)

                        t = New Task(Sub() multiTask({arr(0)}))
                        t.Start()

                        Me.Text = i
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                End While
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        t.Wait()
        MsgBox("Successfully completed.")
        Me.Enabled = True
    End Sub

    Sub multiTask(ByVal Params() As Object)
        Using oConn As SqlConnection = New SqlConnection(ConnectionString)
            Using oCmd As SqlCommand = New SqlCommand
                oConn.Open()
                oCmd.Connection = oConn
                oCmd.Parameters.Clear()
                oCmd.CommandText = "[dbo].[PROC_THAT_DO_SOME_TREATMENTS_AND_INSERT_IN_A_TABLE]"
                oCmd.CommandType = CommandType.StoredProcedure
                oCmd.Parameters.AddWithValue("@ID", Params(0))
                oCmd.ExecuteNonQuery()
            End Using
        End Using
    End Sub

我能够在多线程中 运行 上面的代码 - 而且它 运行 完美 (18000rec/s),但是,线程终止的控制有点棘手,所以我想到了使用 task.wait () 命令在多任务中将代码更改为 运行。

但是当我运行这段代码时,变量的值被覆盖了。这样,我总是读取文件的最后一行。如果我使用 Thread class,这不会发生 - 但是当我使用 Task class 时,是的。 有人知道为什么吗?

在我看来你最好打电话给 Parallel.ForEach。这将自动为您处理并行性,并且会固有地等待所有项目都已处理。我建议这样:

Sub Main()
    Dim filePath As String 'Store file path here.
    Dim lines = File.ReadLines(filePath)

    'This will process the lines of the file in parallel.
    Parallel.ForEach(lines, AddressOf ProcessLine)

    'When you get here, all lines in the file have been processed.
End Sub

'Process one line of text.
Private Sub ProcessLine(line As String)
    '...
End Sub