开发者

C#: Showing a modal progress dialog during a long process

My software requires to store the directory and registry structure for som开发者_运维技巧e 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?


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.


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()).


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 separate 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


ProgressBar p = new ProgressBar();
p.Location = new Point(10, 10);
p.Size = new Size(100, 30);
p.MarqueeAnimationSpeed = 30;
p.Style = ProgressBarStyle.Marquee;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜