views:

71

answers:

3

My software requires to store the directory and registry structure for some particular locations. This usually takes a long time. Let's say I have a method called SaveState() which does that.

I want to wrap this into another method, SaveStateWithProgress(), so that when I call it, a modal dialog appears, which shows a simple progress bar and has a button to cancel the operation. The way I see it I may need to use two threads, although in VB6 or Java I used to get by with the equivalent of Thread.Yield() command - not sure if it is the best practice, and even if there is something similar in C#. What is the best way to go about it?

+2  A: 

The best method in C# is use a BackgroundWorker and run your intensive operation inside that background worker.

Here is a tutorial that includes instructions on how to cancel your operation half way.

Scott Chamberlain
A: 

In C#, you can call Thread.Sleep(0) or Thread.Sleep(1) to do the same thing as Java's Thread.Yield().

With that said, you will definately need to do your SaveState() in a seperate thread. Have a variable in your SaveState() function that gets updated as SaveState() progresses. Put a timer control in your modal progress form and have the timer check this variable that SaveState() is updating. Update your progress bar appropriately

icemanind
It's true that `Thread.Sleep(0)` will yield the current thread, but that does you no good if your UI is running on the same thread. The .NET Framework does have `Application.DoEvents()` to essentially yield to one pass of the message pump loop, but using a `BackgroundWorker` is much to be preferred.
Daniel Pryden
+2  A: 

Here's a site that I think would satisfy what you need.

It has example of using a progress bar and background worker (using BackgroundWorker.RunWorkerAsync()).

rgunawan