Tutorial :C#: Query status of a thread



Question:

I am running a background worker thread that takes a long time to run.

The actual function stores the folder structure of a location, but we can take an example of the following pseudo code running in a different thread -

private int currentResult=0;  private void worker() {      for(int n = 0; n<1000; ++n)      {          int result;          // Do some time consuming computation and update the result          currentResult = result;      }  }  

This is running in a BackgroundWorker thread. Can I read the currentResult from another thread safely?

Edit:

Keyword volatile seems like a magic solution (thanks Jon)! I am planning to pass a string with a message in this way from the worker class to the UI.

You might be wondering why I don't use ReportProgress. The reason is that the BackgroundWorker.DoWork creates an object of a different class, and calls a method there which does bulk of the work. This method is time consuming. The class is one to get the directory structure, and many related methods in it which the main computing method depends on. So this class does not even know existance of the background worker, and hence cannot report progress to it. Moving functionality of the class to BackgroundWorker seems messy. If this strikes as a bad design I am open to suggestions!


Solution:1

If you make it volatile you can... or if you always use the Interlocked class to both read and write it. (Or always read/write it within a lock on the same monitor.) Without these precautions, you could end up reading a stale value.

However, that's not necessarily the best way to do things. Generally, a background worker should use ReportProgress to indicate its progress... is there any reason you don't want to do that in this case?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »