Page 148 - CSharp/C#
P. 148

Chapter 17: BackgroundWorker




        Syntax



            •  bgWorker.CancellationPending //returns whether the bgWorker was cancelled during its
              operation

            •  bgWorker.IsBusy //returns true if the bgWorker is in the middle of an operation

            •  bgWorker.ReportProgress(int x) //Reports a change in progress. Raises the "ProgressChanged"
              event

            •  bgWorker.RunWorkerAsync() //Starts the BackgroundWorker by raising the "DoWork" event

            •  bgWorker.CancelAsync() //instructs the BackgroundWorker to stop after the completion of a
              task.


        Remarks


        Performing long-running operations within the UI thread can cause your application to become
        unresponsive, appearing to the user that it has stopped working. It is preferred that these tasks be
        run on a background thread. Once complete, the UI can be updated.


        Making changes to the UI during the BackgroundWorker's operation requires invoking the
        changes to the UI thread, typically by using the Control.Invoke method on the control you are
        updating. Neglecting to do so will cause your program to throw an exception.

        The BackgroundWorker is typically only used in Windows Forms applications. In WPF
        applications, Tasks are used to offload work onto background threads (possibly in combination
        with async/await). Marshalling updates onto the UI thread is typically done automatically, when the
        property being updated implements INotifyPropertyChanged, or manually by using the UI thread's
        Dispatcher.


        Examples



        Assigning Event Handlers to a BackgroundWorker


        Once the instance of the BackgroundWorker has been declared, it must be given properties and
        event handlers for the tasks it performs.


             /* This is the backgroundworker's "DoWork" event handler. This
                method is what will contain all the work you
                wish to have your program perform without blocking the UI. */

             bgWorker.DoWork += bgWorker_DoWork;


             /*This is how the DoWork event method signature looks like:*/
             private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
             {


        https://riptutorial.com/                                                                               94
   143   144   145   146   147   148   149   150   151   152   153