alwaysVBNET
alwaysVBNET

Reputation: 3310

Waiting for all Tasks in Async to complete

I am trying to run 10 processes simultaneously and when they finish I want to display a messagebox. The UI should remain responsive.

I have this function (MultiProcessImages) which displays a message before all the images finish:

 '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

Then I created another function which makes the UI unresponsive and also the processing does not seem to be multitasking (which means it does not perform all the actions of the CopyBinaryValueToFile in parallel but only for each task number):

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

Any ideas how to make it behave like I have it in the first function but wait until all the processes finish to display a message?

EDIT

I'm calling the function like this:

 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

Upvotes: 0

Views: 1237

Answers (1)

Ric
Ric

Reputation: 13248

Without seeing the rest of your code and the implementation of Cheque.CopyBinaryValueToFile(), the following may help you resolve the issue of UI being blocked:

Within MultiProcessImages2():

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

Upvotes: 1

Related Questions