所以我想检查便携式类库中的互联网连接。
到目前为止,我已经使用了这种方法GetResponse() in C#
但是这不会返回一个布尔值来告诉我是否有连接。
到目前为止,我的代码看起来像这样:
public static bool CheckForInternetConnection()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.UseDefaultCredentials = true;
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}
catch
{
return false;
}
}
private static bool FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
return true;
}
else
{
return false;
}
}
但我在new AsyncCallback()
的行上收到错误,说FinishRequest的返回类型错误..我该怎么做?
请记住,这是在Portable类库中,因此方法GetResponse()不存在
答案 0 :(得分:2)
您可以像这样使用manualresetevent:
private static ManualResetEvent evt = new ManualResetEvent(false);
public static bool CheckForInternetConnection()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.UseDefaultCredentials = true;
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
evt.WaitOne();
return request.HaveResponse;
}
catch
{
return false;
}
}
private static void FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
evt.Set();
}