2013-04-08 16 views
5

Sto utilizzando il seguente codice per ottenere un endpoint e scrivere a una cache:HttpClient non buttare eccezione quando si utilizza attendono GetAsync

public async Task UpdateCacheFromHttp(string Uri) 
{ 
    if (string.IsNullOrEmpty(Uri)) 
     return; 

    var httpClient = new HttpClient(); 
    var response = await httpClient.GetAsync(Uri); 

    if ((response != null) && (response.IsSuccessStatusCode)) 
    { 
     var responseStream = await response.Content.ReadAsStreamAsync(); 
     WriteToCache(responseStream); 
    } 
} 

Il codice è in esecuzione su IIS.

Se non è possibile raggiungere l'endpoint, mi aspetto che GetAsync generi un'eccezione. Anche con Try-Catch, non sembra mai fallire. GetAsync non ritorna mai (ho provato un timeout di 5 secondi su HttpClient, ancora non ho restituito).

Questo non fa un'eccezione:

public Task UpdateCacheFromHttp(string Uri) 
{ 
    var updateCacheTask = Task.Factory.StartNew(new Action(() => 
    { 
     if (string.IsNullOrEmpty(Uri)) 
      return; 

     var httpClient = new HttpClient(); 
     var response = httpClient.GetAsync(Uri).Result; 

     if (response.IsSuccessStatusCode) 
     { 
      var responseStream = response.Content.ReadAsStreamAsync().Result; 
      WriteToCache(responseStream); 
     } 
    })); 

    return updateCacheTask; 
} 

ottengo l'atteso "Impossibile connettersi al server remoto".

Sospetto che abbia qualcosa a che fare con il codice in esecuzione in IIS, ma perché? Come faccio a farlo per lanciare correttamente l'eccezione senza la necessità di iniziare una nuova attività?

risposta

15

La mia intuizione mi dice che stai chiamando Wait o Result oltre lo stack delle chiamate.

Se ciò è corretto, stai causando un deadlock, come I explain on my blog.

+1

Questa è una vera intuizione. Grazie. – Askolein

+4

+1, la tua intuizione è una cosa brillante. – Valentin

Problemi correlati