【发布时间】:2014-09-10 17:40:48
【问题描述】:
我有这个代码:
public static string HttpGet(string URI)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
try
{
SetInterval(() =>
{
string r = HttpGet("http://www.example.com/some.php?Username= Z&Status=On");
}, 10000);
}
catch (WebException) { MessageBox.Show("No Network!"); }
Setinterval() 在重试中的作用是每 10000 毫秒运行一次代码。 但是如果我没有连接到互联网,它会给我一个 WebException 错误。但似乎我什至无法处理它。捕获异常仍然给我同样的错误。发生错误时有什么方法可以说“什么都不做”?
P.S 我是 C# 新手。
编辑: 这是setinterval的代码:
public static IDisposable SetInterval(Action method, int delayInMilliseconds)
{
System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
timer.Elapsed += (source, e) =>
{
method();
};
timer.Enabled = true;
timer.Start();
// Returns a stop handle which can be used for stopping
// the timer, if required
return timer as IDisposable;
}
【问题讨论】:
-
您看到了什么错误?没有网络是您对 WebException 的期望。如果您抛出了另一种异常,那么它仍然会抛出,因为您只是在捕获 WebException。如果您通过 Visual Studio 运行它,那么您仍然会看到一个异常,但是您应该会收到您的消息,再次假设它是 WebException。
-
这是我仍然得到的错误:
An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code Additional information: The remote name could not be resolved: 'example.com' If there is a handler for this exception, the program may be safely continued.
标签: c# exception system.net