C# Windows 服务 While 循环

C# Windows Service While loop

我的 windows 服务有问题。

protected override void OnStart(string[] args)
{
    while (!File.Exists(@"C:\Users\john\logOn\oauth_url.txt"))
    {
        Thread.Sleep(1000);
    }
...

我必须等待一个特定的文件,因此需要 while 循环,但服务将无法像这样循环启动。我可以做些什么来获得 运行 服务和检查文件是否存在的机制?

最好的选择是在您的服务中设置一个定时器System.Timers.Timer

System.Timers.Timer timer = new System.Timers.Timer();

在构造函数中添加 Elapsed 事件的处理程序:

timer.Interval = 1000; //miliseconds
timer.Elapsed += TimerTicked;
timer.AutoReset = true;
timer.Enabled = true;

然后在 OnStart 方法中启动那个计时器:

timer.Start();

在事件处理程序中执行您的工作:

private static void TimerTicked(Object source, ElapsedEventArgs e)
{
    if (!File.Exists(@"C:\Users\john\logOn\oauth_url.txt"))
        return;

    //If the file exists do stuff, otherwise the timer will tick after another second.
}

最低限度的服务 class 看起来有点像这样:

public class FileCheckServivce : System.ServiceProcess.ServiceBase  
{
    System.Timers.Timer timer = new System.Timers.Timer(1000);

    public FileCheckServivce()
    {
        timer.Elapsed += TimerTicked;
        timer.AutoReset = true;
        timer.Enabled = true;
    }

    protected override void OnStart(string[] args)
    {
        timer.Start();
    }

    private static void TimerTicked(Object source, ElapsedEventArgs e)
    {
        if (!File.Exists(@"C:\Users\john\logOn\oauth_url.txt")) 
            return;

        //If the file exists do stuff, otherwise the timer will tick after another second.
    }
}

我会考虑使用 FileSystemWatcher,因为它正是用于监视文件系统上的更改。在文件夹上引发事件后,您可以检查该特定文件是否存在。

MSDN中的默认示例实际上显示了对.txt文件的监控https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx