locked
Caught TimeOut Exception RRS feed

  • Question

  • Hello Everyone, i am developing a wp8 app, i use a HttpClient to perform PostAsync and GetAsync operations, i am setting the timeout to 1 second :

    private HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromMilliseconds(1000); 

    I have a try catch block on my Get and Post operation to caught the TimeOutExceptions as:

    try
    {
        var response = await client.PostAsync(param1,param2);
    }
    catch (TimeoutException e)
    {
        //do something
    }    

    Nevertheless my catch block is not capturing the exception, i debug my app and watch the throwen exception  is a TaskCanceledException, ¿How can i caught the right exception?, ¿Why is the TimeOutException replaced?

    Finally, and to avoid confusion, my real timeout will be 10 seconds, i am using 1 seconds just to test, and i need to show a message to the user if the timeout is exceeded. 

    Wednesday, November 6, 2013 3:11 PM

All replies

  • That is because the synchronization contexts are different. When the method hits await, it actually finished, and the rest of the method(after await) is another method, thus the catch never actually existed. The exception will be caught by the global exception handler.

    If you want to catch the exception, you need to wrap that code in a async Task/Task<T> and not call it from async void.


    • Edited by mcosmin Wednesday, November 6, 2013 3:21 PM
    Wednesday, November 6, 2013 3:21 PM
  • I am not calling it from an async void, the method that containt the previous code has the following signature:

    public async Task<Myclass> MyMethod()

    Wednesday, November 6, 2013 3:35 PM
  • Use a catch without param (it will catch everything).You can use a generic message to tell the user the connection is not working properly.

    If the exception thrown is TaskCanceledException, then you obviously need to catch that exception type.

    Wednesday, November 6, 2013 3:47 PM
  • I understand your point, but in several occasions i have faced network trouble while i performed a debug, and i have saw with my own developer eyes the TimeOutException appear, so i decide to set the timeout value, but now the TimeOutException is not thrown.
    Wednesday, November 6, 2013 3:53 PM
  • It is not thrown because it is handled in the Task you are awaiting. Instead, a TaskCanceledException is thrown, because when the timeout occurs, the task needs to die in eternal fire, and the only way to cancel a thread is to throw an exception.
    Thursday, November 7, 2013 4:51 AM