use*_*850 1 c# windows-services
我有一个Windows服务的问题.
protected override void OnStart(string[] args)
{
while (!File.Exists(@"C:\\Users\\john\\logOn\\oauth_url.txt"))
{
Thread.Sleep(1000);
}
...
Run Code Online (Sandbox Code Playgroud)
我必须等待一个特定的文件,因此while循环是必要的,但服务将无法像这样循环启动.我可以做什么来运行正在运行的服务和检查文件是否存在的机制?
最好的选择是System.Timers.Timer在您的服务中使用计时器.
System.Timers.Timer timer = new System.Timers.Timer();
Run Code Online (Sandbox Code Playgroud)
在构造函数中添加Elapsed事件的处理程序:
timer.Interval = 1000; //miliseconds
timer.Elapsed += TimerTicked;
timer.AutoReset = true;
timer.Enabled = true;
Run Code Online (Sandbox Code Playgroud)
然后在OnStart方法中启动那个计时器:
timer.Start();
Run Code Online (Sandbox Code Playgroud)
在事件处理程序中完成您的工作:
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.
}
Run Code Online (Sandbox Code Playgroud)
最小的服务类看起来有点像这样:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
951 次 |
| 最近记录: |