views:

46

answers:

1

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!

+6  A: 

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?

Jon Skeet
So all I need is "volatile int currentResult=0;"?The BackgroundWorker creates some object from a custom class ('DirectoryStructure') and runs the method there. That method is what takes up the time. Since it is a different class, I cannot use the ReportProgress. One option seems to be transferring functionality of the DirectoryStructure class into the class containing BackgroundWorker, but that seems messy. I am open to suggestions...
KalEl
@KalEl: Just because you're in a different class doesn't mean you can't use ReportProgress. For example, you could pas DirectoryStructure a delegate to call every time it has some progress, and call ReportProgress from that delegate. I really don't think sharing access to the variable is a nice way of communicating here.
Jon Skeet
Thanks, makes sense.
KalEl