我正在使用 Android 模拟器使用 MonoDevelop/C# 测试为 Android(以及后来的 iphone)开发应用程序。
我有一个 WebRequest,我想在它超时(或没有网络连接)时得到一个回调。起初,如果互联网连接中断,我没有超时或回调。以下是我尝试解决的方法:
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)
{ ... }