Search code examples
c#classbackgroundworker

BackgroundWorker ProgressChanged in a form being triggered from a separate class


I'm new to C# and am trying to wrap my mind around object oriented programming. Here's what I am trying to accomplish:

I've got a Windows Form application with Form1 and a separate class called connect (same namespace).

I understand that it is good practice to use backgroundworkers when executing lengthy amounts of code (so as not to freeze the UI). So I've created a background worker in Form1 and a progresschanged handle. I'm trying to find how in the separate connect class I can trigger a progresschange. In the progresschange block in Form1 I have a case/switch which determines what text shows on the screen.

What is the best way to approach this? Shall I pass the backgroundworker to the other class?


Solution

  • You could break your steps of the connect class into separate methods and invoke them sequentially as below.You dont have to trigger the progresschanged event from connect class object.

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
         ConnectClass conObject= new ConnectClass();
         backgroundWorker.ReportProgress(30, "Connecting ...");
         conObject.Connect();
         backgroundWorker.ReportProgress(30, "Connected."+"\n Executing query");
         conObject.Execute();
         backgroundWorker.ReportProgress(40, "Execution completed.");
    }