Progress Bar for unknown process time
I am developing winform(c#) that start/stop/restart windows services. I want to put a progress bar till the action is completed. I am new to .net programming. Kindl开发者_如何学Cy help me on to achieve this.
You cannot show meaningful progress when you don't know how long it takes. You can't know, services take anywhere from 1 to 30 seconds to start. All you can do is show a "I'm not dead, working on it" indicator to the user. ProgressBar supports that, set the Style property to "Marquee".
You'll also need to start the service in a worker thread to avoid your UI from freezing. That's best done with a BackgroundWorker. Make it look similar to this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
ServiceProgressBar.Style = ProgressBarStyle.Marquee;
ServiceProgressBar.Visible = false;
}
private void StartButton_Click(object sender, EventArgs e) {
this.StartButton.Enabled = false;
this.ServiceProgressBar.Visible = true;
this.backgroundWorker1.RunWorkerAsync("foo");
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
var ctl = new ServiceController((string)e.Argument);
ctl.Start();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
this.StartButton.Enabled = true;
this.ServiceProgressBar.Visible = false;
if (e.Error != null) {
MessageBox.Show(e.Error.ToString(), "Could not start service");
}
}
You must divide up the start/stop/restart progress in small parts and after the part is finished you set the progress bar.
For an instant update you need to get into the methods you are executing to get feedback about its status.
Do you mean that you want to start/restart/stop more than one service and want the progress bar to indicate "how far you've processed the list of services to be started/restarted/stopped"? You could do something like:
progressBar.Maximum = listOfServicesToStart.Count;
progressBar.Value = 0;
for (int i = 0; i < listOfServicesToStart.Count; i++)
{
// Start service listOfServicesToStart[i]
progressBar.Value = i;
Application.DoEvents();
}
If you are planning to visualize the starting process of a service: I guess you can't do it nicely. What the Services snap-in in Windows seems to do is:
- It tries to start/restart/stop the service
- It calls
ServiceController.WaitForStatus
with a 1sec timeout to see whether the service has entered the respective state - Increases the progress bar value by one and goes to 2. until a timeout is detected (you need to find a reasonable number of seconds to wait for the service to enter the desired state)
This seems to be the only way.
精彩评论