未知进程时间的进度条 [英] Progress Bar for unknown process time
问题描述
我正在开发启动/停止/重启 Windows 服务的 winform(c#).我想放置一个进度条,直到操作完成.我是 .net 编程的新手.请帮助我实现这一目标.
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. Kindly help me on to achieve this.
推荐答案
当您不知道需要多长时间时,您无法显示有意义的进展.您无法知道,服务需要 1 到 30 秒才能启动.您所能做的就是向用户显示我还没死,正在努力"的指示.ProgressBar 支持,将 Style 属性设置为Marquee".
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".
您还需要在工作线程中启动该服务,以避免您的 UI 冻结.最好使用 BackgroundWorker 来完成.让它看起来像这样:
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");
}
}
这篇关于未知进程时间的进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!