How to wait correctly until BackgroundWorker completes?

前端 未结 10 1211
既然无缘
既然无缘 2020-12-02 11:19

Observe the following piece of code:

var handler = GetTheRightHandler();
var bw = new BackgroundWorker();
bw.RunWorkerCompleted += OnAsyncOperationCompleted;         


        
10条回答
  •  孤城傲影
    2020-12-02 11:45

    This question is old but I don't think the author got the answer he was looking for.

    This is a bit dirty, and it's in vb.NET but works for me

    Private Sub MultiTaskingForThePoor()
        Try
            'Start background worker
            bgwAsyncTasks.RunWorkerAsync()
            'Do some other stuff here
            For i as integer = 0 to 100
                lblOutput.Text = cstr(i)
            Next
    
            'Wait for Background worker
            While bgwAsyncTasks.isBusy()
                Windows.Forms.Application.DoEvents()
            End While
    
            'Voila, we are back in sync
            lblOutput.Text = "Success!"
        Catch ex As Exception
            MsgBox("Oops!" & vbcrlf & ex.Message)
        End Try
    End Sub
    

提交回复
热议问题