0

In the example below, I use the ReportProgress functionality of the BackgroundWorker:

    void MyMethod()
    {
        if (!File.Exists)
        {
            bw.ReportProgress(0, "Error");
        }
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        this.MyMethod1();
        this.MyMethod2();
        this.MyMethod3();
    }

    private void bw_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    {
        string error = e.UserState as String;
        if (!string.IsNullOrEmpty(error)
        {
             // stop BackgrowndWorker
        }
    }

In every MyMethod() i check something and do ReportProgress. If there are possibilities to correctly stop BackgroundWorker in my case?

Need i to change the way of my code architecture?

Konstantin
  • 796
  • 1
  • 11
  • 32
  • possible duplicate of [How to stop BackgroundWorker correctly](http://stackoverflow.com/questions/4732737/how-to-stop-backgroundworker-correctly) – Erki M. Jul 19 '15 at 13:16
  • 2
    Not much point in doing this the hard way. Simply throw an exception, boom, over. Your RunWorkerCompleted event handler can obtain the e.Error property and report the mishap. – Hans Passant Jul 19 '15 at 13:24
  • OK. I understand. I would suggest this way in my question, but now i'm sure that throw BOOM is correct way. Thank you. – Konstantin Jul 19 '15 at 13:36

1 Answers1

1

The ReportProgress method is to... report progress. The only thing you can pass in is an percentage and the user state. That's all. You shouldn't use it to pass in an error.

Instead, the best thing you can do is to throw an exception. This will bubble up till the RunWorkerCompleted event handler, which has an event argument property named Error. Check that property in the event handler you write and you know what went wrong.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325