问题描述
|
我正在开发启动/停止/重新启动Windows服务的winform(c#)。我想放置一个进度条,直到操作完成。我是.net编程的新手。请帮助我实现这一目标。
解决方法
当您不知道需要多长时间时,您将无法显示有意义的进度。您不知道,服务启动需要1到30秒。您所能做的就是向用户显示一个“我还没死,正在努力”指示器。 ProgressBar支持该功能,将Style属性设置为\“ Marquee \”。
您还需要在辅助线程中启动服务,以避免UI冻结。最好使用BackgroundWorker完成。使它看起来与此类似:
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\");
}
}
, 您必须将开始/停止/重新启动进度分为小部分,并在完成部分后设置进度条。
对于即时更新,您需要进入正在执行的方法以获取有关其状态的反馈。
, 您是否要启动/重新启动/停止一项以上的服务,并希望进度条指示“您已经完成了要启动/重新启动/停止的服务列表的处理”?您可以执行以下操作:
progressBar.Maximum = listOfServicesToStart.Count;
progressBar.Value = 0;
for (int i = 0; i < listOfServicesToStart.Count; i++)
{
// Start service listOfServicesToStart[i]
progressBar.Value = i;
Application.DoEvents();
}
如果您打算可视化服务的启动过程:我想您做得不好。 Windows中的“服务”管理单元似乎可以执行以下操作:
它尝试启动/重新启动/停止服务
它以1秒的超时时间呼叫ServiceController.WaitForStatus
,以查看服务是否已进入相应状态
将进度条的值增加1并转到2。直到检测到超时(您需要找到合理的秒数才能等待服务进入所需的状态)
这似乎是唯一的方法。