我创建了一个窗口服务,它会在检测到我的数据库发生更改时停止。
问题:如何通过C#编码在5秒或10秒后停止再次启动窗口服务?
private static string connectString = ConfigurationManager.ConnectionStrings['ConnStr'].ToString();
int sql_depend = 0;//stop
private delegate void GridDelegate(DataTable table);
private SqlDependency dep;
public Watcher()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
SqlDependency.Start(connectString);
sql_depend = 1;
UpdateGrid();
string file = @"E:\WatcherLogFile\sds.txt";
TextWriter writer = new StreamWriter(file, true);
writer.WriteLine("Window services started");
writer.Close();
}
protected override void OnStop()
{
string file = @"E:\WatcherLogFile\sds.txt";
TextWriter writer = new StreamWriter(file, true);
writer.WriteLine("Window services stopped");
writer.Close();
}
//sql dependency check
private void UpdateGrid()
{
string sql = "select [Name], [ClientName] from [Account]";
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(connectString))
{
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cn.Open();
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
}
}
}
//sql dependency detect changes
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
ServiceController myService = new ServiceController();
myService.ServiceName = "Watcher";
myService.Stop();
SqlDependency.Stop(connectString);
sql_depend = 0;
}
答案 0 :(得分:0)
你可以试试这个。
var sc = new ServiceController(YouServiceNameString);
// stop service
// sc.Stop();
//start service
sc.Start();
// or restart
/*
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
*/
如果要暂停,请使用Thread.Sleep或此示例
var _stopToken = new CancellationTokenSource();
// call this when you want stop
// _stopToken.Cancel();
// there is you can set timeout
_stopToken.Token.WaitHandle.WaitOne(YourWaitTime);
// if you want circle
// while (!_stopToken.IsCancellationRequested)
// { /*...do somthing...*/ }
答案 1 :(得分:0)