我正在使用Android模拟器使用MonoDevelop / C#测试为Android(以及后来的iphone)开发应用程序。
我有一个WebRequest,我希望在超时(或没有webconnection)时获得回调。首先,如果互联网连接中断,我没有超时或回叫。以下是我试图解决的问题:
private void setupTimeOut (IAsyncResult result, RequestState state)
{
ThreadPool.RegisterWaitForSingleObject (
result.AsyncWaitHandle,
new WaitOrTimerCallback (ScanTimeoutCallback),
state,
(5 * 1000), // 5 second timeout
true
);
}
正确地说,ScanTimeoutCallback在5秒后被调用(当我拔掉互联网时)。但是ScanTimeout确实抛出了这个异常:
UNHANDLED EXCEPTION: System.Net.WebException: Aborted.
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult) <0x00160>
at MyApp.ServerService.extractResponseAndCallDelegateOnError
(System.Net.WebRequest,System.IAsyncResult) <0x0003b>
ScanTimeoutCallback的代码:
private static void ScanTimeoutCallback (object state, bool timedOut)
{
if (timedOut)
{
Console.Out.WriteLine ("timedOut");
RequestState reqState = (RequestState)state;
if (reqState != null)
{
reqState.Request.Abort ();
//Call my UI callback
}
}
}
BeginGetResponse:
IAsyncResult result = request.BeginGetResponse (o => {
context.Post (_ => {
onLogin (o); }, null);
}, state);
setupTimeOut (result, state);
EndGetResponse:
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result) as HttpWebResponse)
{ ... }
答案 0 :(得分:1)
超时没有抛出异常,而是由EndGetResponse
处理程序抛出。
您需要在处理程序中处理异常:
try
{
using (HttpWebResponse response ...)
{
...
}
}
catch (System.Net.WebException)
{
// handle the exception here
}