vb.net - 使用参数化函数 (x, y, z) 的 for 循环中的多个线程

标签 vb.net multithreading

我有一个包含文件夹 ID 和文件夹路径的列表。我想将其中一些文件夹传递给压缩它们的函数。我想要的是让三个线程并行运行并一次压缩三个不同的路径。现在发生的情况是每个线程都会等待,直到下一个线程完成才能处理下一个线程。有什么想法吗?

Dim SelectedRange = From folders In listFolders Where folders.FolderID >= 150101

For Each item In SelectedRange
    Dim t As New Thread(
        Sub()
            Me.BeginInvoke(DirectCast(Sub() ZipFolder(sInclearDestination, item.FolderID.ToString, item.FolderPath), MethodInvoker))
        End Sub)
    t.Start()
    t.Join()
Next

Public Function ZipFolder(ByVal sFolderPathDestination As String, ByVal folderID As String, ByVal folderPath As String) As Boolean
    Try
        Using zip = New Ionic.Zip.ZipFile()
            'If the zip file does not exist then get the folder and zip it to the destination
            If Not File.Exists(Path.Combine(sFolderPathDestination, folderID & ".zip")) Then
                zip.AddDirectory(folderPath)
                zip.Save(Path.Combine(sFolderPathDestination, CType(folderID, String) & ".zip"))
                Return True
            Else
                Logging.Log("Aborting zipping: " & Path.Combine(sFolderPathDestination, folderID & ".zip") & ". The zip file already exists!")
                Return False
            End If
        End Using
    Catch ex As Exception
        Logging.Log("Error in zipping: " & Path.Combine(sFolderPathDestination, folderID & ".zip") & " Error: " & ex.Message)
        Return False
    End Try
End Function

最佳答案

您的代码有两个问题。

第一个问题是对Me.BeginInvoke的调用。假设您正在创建一个 WinForm 应用程序,而 Me 是对当前 Form 的引用。 Form.BeginInvoke(继承自 Control 基类)导致给定委托(delegate)在 UI 线程上执行。因此,您所做的就是创建三个独立的线程,它们都立即调用回 UI 线程来完成所有工作。显然,您不能在这样做的同时仍然期望任务能够并行处理。您需要删除对 BeginInvoke 的调用。如果您需要调用 BeginInvoke 来更新表单上某些数据的显示,则需要尽可能晚地执行此操作,并在 UI 调用的代码中执行尽可能少的工作,以便大部分工作仍在工作线程中完成。

第二个问题是对Thread.Join的调用。您在启动线程后立即在 For 循环中调用 Join 。这意味着它将在调用 Join 时坐在那里等待,直到工作线程完成。因此,您的循环会等待每个线程完成,然后再启动下一个线程,本质上使其成为单线程。您应该删除对 Join 的调用。如果您需要调用方法等待所有线程完成,只需等待在线程上调用Join,直到所有线程都已启动(即在 >For 循环)。

关于vb.net - 使用参数化函数 (x, y, z) 的 for 循环中的多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28199662/

相关文章:

javascript - (VB) 通过 javascript 使用 Url.Action 传递文本框值

c# - 正则表达式排除括号

javascript - ASP.Net 模态页面代码未触发

multithreading - 在多线程上下文中使用带有生菜的 Spring-Data-Redis 的 OutOfDirectMemoryError

c# - 如何使 .NET COM 对象成为单元线程?

c# - 使用 EPPlus (asp.net) 在 excel 中转换为整数

vb.net - 在VB中添加错误处理程序

java同步和对象锁

java - 如何在 4 个独立线程完成后安排打印语句?

c++ - 在不阻塞的情况下唤醒多个等待线程的最便宜方法