Search code examples
c#multithreadingbackgroundworker

How can I fit my code into a Background Worker?


I've built out a form that does the following:

  1. Grabs all the file paths in a directory (files are in a specified naming convention)
  2. Parses file paths using a delimiter
  3. Outputs a text file with a specified format.

The issue is that some directories are hundreds of gigs which freezes the form UI until the process is done. I've done some reading on Background workers and to my understanding, the data intensive part of your code goes under the DoWork method. However when I try implementing my code into the DoWork method I run into the "Cross-thread operation not valid:" error. I looked up the error but I simply don't understand how I can work around this error without reworking the entire structure of my program.

My code is quite lengthy but I can supply if needed.


Solution

  • The best way is to rework your code so it doesn't use UI components.

    Once it's done you can use ReportProgress/ProgressChanged and RunWorkerCompleted to refresh the UI.

    If you still want to use UI components, you may try Invoke :

    this.Invoke(new Action(() => 
        {
            //code that uses UI for instance :
            //this.TextBox1.Text = "test"
        });