【发布时间】:2014-05-30 08:58:44
【问题描述】:
我一直在尝试实现一个可以保持 vpn 连接有效的 Windows 服务。我发现可以通过订阅RasConnectionWatcher.Disconnected 事件来使用DotRas 库:
public class SampleService {
public SampleService() {
this.shutdownEvent = new ManualResetEvent(false);
this.connectionWatcher = new RasConnectionWatcher();
this.connectionWatcher.Disconnected += onVpnDisconnected;
}
// redial
void onVpnDisconnected(Object sender, RasConnectionEventArgs e) {
this.DialUp();
}
void DialUp() {
// connection setup is omitted
// keep the handle of the connection
this.connectionWatcher.Handle = dialer.Dial();
}
public void Start() {
this.thread = new Thread(WorkerThreadFunc);
this.thread.IsBackground = true;
this.thread.Start();
}
public void Stop() {
this.shutdownEvent.Set();
if(!this.thread.Join(3000)) this.thread.Abort();
}
private void WorkerThreadFunc() {
this.DialUp();
while(!this.shutdownEvent.WaitOne(0)) Thread.Sleep(1000);
}
}
当我启动服务时,vpn 连接打开没有任何问题,但是当我手动中断连接时,Disconnected 事件似乎没有启动。
【问题讨论】:
标签: c# .net multithreading windows-services