【问题标题】:Multi task overriding variables多任务覆盖变量
【发布时间】:2018-04-12 03:52:50
【问题描述】:

首先对不起我的英语不好!

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

我有两个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),但是,线程终止的控制有点棘手,所以我考虑使用任务更改代码以在多任务中运行.wait() 命令。

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

【问题讨论】:

    标签: vb.net multithreading multitasking overriding


    【解决方案1】:

    在我看来,您最好致电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
    

    【讨论】:

    • 我会试试你说的方式——我不知道怎么做。谢谢!我一实施就在此处发布反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2018-09-27
    • 2017-02-25
    • 2021-08-24
    • 2020-09-30
    • 2015-12-04
    • 2013-06-06
    相关资源
    最近更新 更多