How to wait correctly until BackgroundWorker completes?

前端 未结 10 1191
既然无缘
既然无缘 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 12:09

    not quite sure what u mean by waiting. Do you mean that you want something done (by the BW) after thats done you want to do something else? Use bw.RunWorkerCompleted like you do (use a seperate function for readability) and in that callback function do you next stuff. Start a timer to check if the work doesnt take too long.

    var handler = GetTheRightHandler();
    var bw = new BackgroundWorker();
    bw.RunWorkerCompleted += (sender, args) =>
    {
      OnAsyncOperationCompleted(sender, args);
    });
    bw.DoWork += OnDoWorkLoadChildren;
    bw.RunWorkerAsync(handler);
    
    Timer Clock=new Timer();
    Clock.Interval=1000;
    Clock.Start();
    Clock.Tick+=new EventHandler(Timer_Tick);
    
    public void Timer_Tick(object sender,EventArgs eArgs)
    {   
        if (bw.WorkerSupportsCancellation == true)
        {
            bw.CancelAsync();
        }
    
        throw new TimedoutException("bla bla bla");
     }
    

    In the OnDoWorkLoadChildren:

    if ((worker.CancellationPending == true))
    {
        e.Cancel = true;
        //return or something
    }
    

提交回复
热议问题