I have the following function that downloads a web page:
static bool myFunction(int nmsTimeout, out string strOutErrDesc)
{
//'nmsTimeout' = timeout in ms for connection
//'strOutErrDesc' = receives error description as string
bool bRes = false;
strOutErrDesc = "";
HttpClient httpClient = null;
System.Threading.Tasks.Task<string> tsk = null;
try
{
httpClient = new HttpClient();
tsk = httpClient.GetStringAsync("https://website-to-connet.com");
if (tsk.Wait(nmsTimeout))
{
if (tsk.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
{
string strRes = tsk.Result;
strRes = strRes.Trim();
if (!string.IsNullOrWhiteSpace(strRes))
{
bRes = true;
}
else
{
//Empty result
strOutErrDesc = "Empty result";
}
}
else
{
//Bad task completion
strOutErrDesc = "Bad completion result: " + tsk.Status.ToString();
}
}
else
{
//Timed out
strOutErrDesc = "Timeout expired: " + nmsTimeout + " ms.";
}
}
catch (Exception ex)
{
//Error
strOutErrDesc = "Exception: " + ex.Message;
if (tsk != null)
{
strOutErrDesc += " -- ";
int c = 1;
foreach(var exc in tsk.Exception.InnerExceptions)
{
strOutErrDesc += c.ToString() + ". " + exc.InnerException.Message;
}
}
bRes = false;
}
return bRes;
}
I thought that my try/catch construct was enough to catch all exceptions in it.
Until I found the following exception and the Windows error message that the app crashed:
Unhandled Exception: System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 503 (Service Unavailable).
--- End of inner exception stack trace ---
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
What is this and how do I catch it?

awaitkeyword to see it fixes it. - c00000fdawait.... but moving it to4.5just to fix this "overthought" GC exception is kinda silly. Any other idea how I can catch it in .net 4.0? The annoying thing is that I can't even repro it. If I give it the wrong URL to open, it's caught in mytry/catchblock. - c00000fdWaitfunction (like 1 ms) while requesting a page that does not return success (as your 503 example). Then it should fail. After that you just need to wait or force garbage collection (GC.Collect()) and the finalizer thread should throw the exception. - OrdoshsenGC.Collect();after mytsk.Wait(1). In this case theWaitfunction simply returnsfalseandGC.Collect();does nothing. In other words, no exception. If I make the timeout larger, in this example,tsk.Wait()throws theSystem.AggregateExceptionthat is caught in mytry/catchblock. The question is how did it crash in my screenshot? (So here's your "safe" code.) - c00000fd