如何在c#停止时自动启动窗口服务

时间:2015-06-01 03:22:22

标签: c#

我创建了一个窗口服务,它会在检测到我的数据库发生更改时停止。

问题:如何通过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;
    }
  • 可以是onStop()中的循环函数吗?我希望它每天手动启动一次,然后在此之后自动启动/停止。

2 个答案:

答案 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)

您可以通过各种方式解决问题。

最简单的解决方案是为服务失败配置恢复操作。

查看此link以获取详细说明。

Check here

我可以考虑编写自定义脚本/程序以便在发现故障时重新启动它。