【问题标题】:Wait for threads to finish before carrying on等待线程完成后再继续
【发布时间】:2013-04-25 17:44:11
【问题描述】:

我有许多线程需要运行(大约 160 个)创建文件,然后将它们复制到不同的地方:

'Files is basically a list of strings
'which is passed to a function that creates a file from a number of database fields
'when thats done it copies it to a number of places

       For Each x In Files
            Dim Evaluator = New Thread(Sub() API.Files.Create.Standard(x))
            Evaluator.Start()
        Next

我想要它做的是关闭 160 个左右的线程(使用许可程序 x)然后等待所有线程完成,然后继续执行程序的其余部分。

【问题讨论】:

    标签: vb.net multithreading


    【解决方案1】:

    如果您使用的是 Framework 4.0(对于 3.5,Jon Skeet 有解决方案 @Can I use the task parallel library in a .Net 3.5 project?)。您可以使用 TPL(任务处理库),而不是使用 Thread。它是线程的包装器。所以简而言之,创建任务,它有静态方法 Task.WailAll 允许预期的功能。

    Dim tasks = New Task(160) {}
    For i As var = 0 To 160
        Dim x = i
        tasks(i) = Task.Factory.StartNew(Function() New CreateFileClass(x).[Do]())
    Next
    
    Task.WaitAll(tasks)
    

    我使用了来自Task Parallel Library - Know when all tasks are finished 的代码,并使用上面代码生成的在线 C# 到 VB.Net 转换器。希望对你有帮助。

    【讨论】:

    • Dim x = i 是多余的,否则是一个很好的答案。我打算用类似的解决方案发布我的,但你早点做到了。 +1
    • 我同意这是多余的。邪恶的复制/粘贴:)。
    • 如果走 TPL 路线,OP 的情况甚至可以通过直接的Parallel.ForEach(Files, Sub(x) API.Files.Create.Standard(x)) 变得更简单。
    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-05-21
    • 1970-01-01
    • 2015-10-03
    • 2013-11-25
    相关资源
    最近更新 更多