等待Async中的所有任务完成

时间:2015-08-04 11:35:16

标签: vb.net multithreading asynchronous

我正在尝试同时运行10个进程,当它们完成时我想显示messageboxUI应该保持响应。

我有这个功能(MultiProcessImages),它在所有images完成之前显示一条消息:

 'Start multi processing of images
    Public Shared Async Function MultiProcessImages() As Task
        'Create a task factory and add 10 process one for each ending image number
        Dim t As Task = Nothing
        For i As Integer = 0 To 9
            Dim temp_i As Integer = i
            t = Task.Factory.StartNew(Function() Cheque.CopyBinaryValueToFile(temp_i))
            Await t
        Next
    End Function

然后我创建了另一个使UI无响应的函数,并且处理似乎不是多任务处理(这意味着它不会并行执行CopyBinaryValueToFile的所有操作,而只是针对每个任务号码):

Public Shared Async Function MultiProcessImages**2**() As Task
        Dim tasks As New List(Of Task)()
        For i As Integer = 0 To 9
            Dim temp_i As Integer = i
            tasks.Add(Cheque.CopyBinaryValueToFile(temp_i))
            ' tasks.Add(Task.Factory.StartNew(Function() Cheque.CopyBinaryValueToFile(temp_i)))
        Next
        Await Task.WhenAll(tasks)
        MessageBox.Show("done")
    End Function

任何想法如何使其表现得像我在第一个函数中的表现,但等到所有进程完成才能显示消息?

修改

我正在调用这样的函数:

 Private Async Sub cmdConvert_Click(sender As Object, e As EventArgs) Handles cmdConvert.Click
        'Await Cheque.CopyBinaryValueToFile()
        '{Time count
        Dim start_time As DateTime
        Dim stop_time As DateTime
        Dim elapsed_time As TimeSpan
        start_time = Now
        '}

        Await Cheque.MultiProcessImages2()

        '{Time count
        stop_time = Now
        elapsed_time = stop_time.Subtract(start_time)
        MessageBox.Show("elapsed_time = " & stop_time.Subtract(start_time).ToString & Environment.NewLine _
        & elapsed_time.TotalSeconds.ToString("0.000000"))
        '}
    End Sub

1 个答案:

答案 0 :(得分:1)

如果没有看到代码的其余部分和Cheque.CopyBinaryValueToFile()的实现,以下内容可帮助您解决阻止UI的问题:

MultiProcessImages2()内:

tasks.Add(Task.Run(Function() Cheque.CopyBinaryValueToFile(temp_i)))