简体   繁体   English

c#Timer:系统唤醒后的HTTP连接错误

[英]c# Timer: HTTP connection error after system wake-up

I have a Timer in a C# app (Win7 64). 我在C#应用程序(Win7 64)中有一个计时器。 Every 20 min the timer callback gets some data via HTTP. 计时器回调每20分钟通过HTTP获取一些数据。 It works well. 它运作良好。 But if my PC goes to sleep for a few hours, then wakes up, I get an HTTP error saying "can't find the server". 但是,如果我的PC进入睡眠状态几个小时,然后醒来,我会收到一条HTTP错误,提示“找不到服务器”。 The server is running at all times, so it's not the real issue. 服务器一直在运行,所以这不是真正的问题。 I suspect the real reason is that as the timer callback misses its "time slot" during the sleep period, it becomes "overdue" and is executed instantly right after the wake-up, without waiting for the PC to re-establish the Internet connection. 我怀疑真正的原因是,由于计时器回调在睡眠期间错过了它的“时间段”,它变得“过期”并在唤醒后立即执行,而无需等待PC重新建立Internet连接。 I can fix the problem by adding a Thread.Sleep(5000) at the beginning of the callback, but it's a bit of a kludge (establishing Internet connection might take longer). 我可以通过在回调开始时添加Thread.Sleep(5000)来解决问题,但它有点像kludge(建立Internet连接可能需要更长时间)。 My questions: 我的问题:

  1. After a wake-up from sleep mode, does Win indeed need a few seconds to re-establish Internet connection? 从睡眠模式唤醒后,Win是否确实需要几秒钟来重新建立Internet连接? My connection is DSL, "always online". 我的连接是DSL,“永远在线”。

  2. Is there a C# system call which would wait until Win establishes the Internet connection (or time out if this doesn't happen within, say, 20 secs)? 是否存在C#系统调用,等待Win建立Internet连接(或者如果在20秒内没有发生这种情况则超时)?

EDIT: Just found this: Check Net connection in C# . 编辑:刚刚发现: 检查C#中的网络连接 Not as simple as I hoped, it takes a sequence of checks: any LAN connection, DNS lookup (outside the LAN), ping a server (check a particular server). 不像我希望的那么简单,它需要一系列检查: 任何 LAN连接,DNS查找(LAN外),ping服务器(检查特定服务器)。

1) Yes 2) You may check various connection attributes via WMI for example. 1)是2)例如,您可以通过WMI检查各种连接属性。 See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394595%28v=vs.85%29.aspx and http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216%28v=vs.85%29.aspx to make sure you have a connection before attempting a query. 请参阅: http : //msdn.microsoft.com/en-us/library/windows/desktop/aa394595%28v=vs.85%29.aspxhttp://msdn.microsoft.com/en-us/library/ windows / desktop / aa394216%28v = vs.85%29.aspx以确保在尝试查询之前有连接。

I don't think you should bother with WMI and such. 我认为您不应该为WMI之类而烦恼。

If you cannot access the network, set the timer to fire in a minuts instead of 20. You alrsady have a waiting mechanism in place, reusing it will not seem kludgy. 如果您无法访问网络,则将计时器设置为在分钟内而不是20分钟内触发。一直以来,您都有一个等待机制,重用它似乎不太灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM