开发者

How to use Progressbar in Button Click without BackGroundworker [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_如何学编程 Closed 10 years ago.

I am working with C#.net,Windows application ,I would like o use Progressbar in Button Click without BackGroundworker ,can any one suggest ,thanks in advance....................,I tried using thread ,For loop iteration,


The quick answer is pretty close to "you can't".

The longer answer is:

Theoretically you could simply start a progress bar, and then update it within a for() loop.

However, this doesn't work very well in practice. The reason is that while you're in your loop, your application is "busy" and it does not respond to the windows messages coming in from the OS. The OS will notice this and decide that you're being unresponsive, so it takes a snapshot of your window. From that point on, whenever you update your progress bar, the OS just displays the snapshot instead of the current state, so as far as the user is concerned, the progress bar moved to (e.g.) 35% and then just got "stuck". THis completely defeats the point of having a progress bar!

To fix this, your UI thread must keep processing messages. There are two ways this can be done.

1) Use a separate thread for the processing job, and ask the UI thread to update the progress bar. This is the "Background Worker" approach, and it works well.

2) You can call Application.DoEvents() from within your fixed for() loop. This allows messages to be dispatched while you are "busy" and thus avoids the problem. Howeve,r this is extremely dangerous as processing messages can cause re-entrant calls to your code (e.g. if you click a "go" button to start processing, the user would be able to click "go" again and you would try to do some processing inside your processing). To fix this you have to be quite careful, installing a MessageFilter to make sure that you only process "safe" messages in this context. Don't attempt this approach unless you really know what you're doing.

So that leaves you with only one practical approach: Use a BackgroundWorker (or your own thread). There are plenty of tutorials on how to do this on the web, so I won't elaborate on that approach here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜