多任务覆盖变量

广州的费尔南多

首先抱歉我的英语不好!

那么现在,我的问题是:我有一个需要快速运行的进程——它有大量数据,我想以多线程/多任务方式运行——(我不知道这是否是最好的方法)

我有两个 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 类,这不会发生 - 但是当我使用 Task 类时,是的。有谁知道为什么?

杰姆西尼

在我看来,你最好打电话给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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章