View Single Post
  #2 (permalink)  
Old November 27th, 2013, 12:34 AM
Rod Stephens's Avatar
Rod Stephens Rod Stephens is offline
Wrox Author
Points: 3,166, Level: 23
Points: 3,166, Level: 23 Points: 3,166, Level: 23 Points: 3,166, Level: 23
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Jan 2006
Location: , , .
Posts: 647
Thanks: 2
Thanked 96 Times in 95 Posts

1) add a counter (loop) on the number of files found – is it in //Search for files
Do you mean make a counter show you the number of files found as the program searches for them? This could be hard because normally you would use Directory.GetFiles or something similar to do the search and that doesn't return until it is finished. It's also pretty fast so it wouldn't be worth displaying a counter.

Now if you're performing some slower search, that's different. For example, if you need to look through every file in a big hierarchy and then search through the files for some sort of target text, that would be slow enough. Then what you would do is update the display whenever you felt like it. For example, you could update a Label whenever you found a file. Or perhaps after every 100 files you check. (Or every 10 files if the search is slow enough.)

To use a progress bar, you would need to know how far through the task you are. You set its Minimum and Maximum properties to indicate how big the task is. For example, if you are searching 1000 files, you could set Minimum = 0 and Maximum = 1000. Then every now and then, you set Value = # files you have checked. You may also have to call the control's Refresh method to make it refresh before you continue searching.

2) sample code for “BackgroundWorker” and “ProgressBar”

BackgroundWorker does some work in its DoWork method. Whenever it wants to tell the main program about its progress, it should call its ReportProgress method. It should pass into that method a measure of how much progress it has made.

The main program should then catch its ProgressChanged event. That event handler can then display the progress to the user, for example, with a progress bar.

It seems a bit awkward to do it this way but it's what you have to do. The reason is only the thread that built the user interface can directly interact with the interface controls. That means the background worker's working thread cannot directly update labels, progress bars, etc. Instead it calls ReportProgress which raises the ProgressChanged event. The main UI thread catches that event and it IS allowed to modify the controls.

For a BackgroundWorker examples, see:

I hope that helps. Let me know if you get stuck or if I've been unclear.

Rod Stephens, Microsoft MVP

Essential Algorithms: A Practical Approach to Computer Algorithms

(Please post reviews at Amazon or wherever you shop!)