2016-05-17 14 views
12

Sto tentando di utilizzare Func con il metodo Async. E sto ottenendo un errore.Utilizzo del delegato Func con metodo Async

Impossibile convertire l'espressione lambda async per delegare il tipo 'Func<HttpResponseMesage>'. Un'espressione lambda async può restituire void, Task o Task<T>, nessuno dei quali è convertibile in 'Func<HttpResponseMesage>'.

di seguito è il mio codice:

public async Task<HttpResponseMessage> CallAsyncMethod() 
{ 
    Console.WriteLine("Calling Youtube"); 
    HttpClient client = new HttpClient(); 
    var response = await client.GetAsync("https://www.youtube.com/watch?v=_OBlgSz8sSM"); 
    Console.WriteLine("Got Response from youtube"); 
    return response; 
} 

static void Main(string[] args) 
{ 
    Program p = new Program(); 
    Task<HttpResponseMessage> myTask = p.CallAsyncMethod(); 
    Func<HttpResponseMessage> myFun =async() => await myTask; 
    Console.ReadLine(); 
} 
+1

Ho un post sul blog [tipi di delegati asincroni] (http://blog.stephencleary.com/2014/02/synchronous-and-asynchronous-delegate.html) che potresti trovare utile. –

risposta

21

Come dice l'errore, i metodi asincroni restituiscono Task, Task<T> o void. Quindi, per arrivare a questo lavoro è possibile:

Func<Task<HttpResponseMessage>> myFun = async() => await myTask; 
+1

Ricorda che l'operazione asincrona potrebbe non essere completata quando l'utente preme un tasto e 'Console.ReadLine()' ha finito. L'app potrebbe terminare prima che l'operazione asincrona sia terminata, a meno che non si attivi 'Wait' su' Task'. –

1

codice fisso come ad esempio:

static void Main(string[] args) 
     { 
      Program p = new Program(); 
      Task<HttpResponseMessage> myTask = p.CallAsyncMethod(); 
      Func<Task<HttpResponseMessage>> myFun = async() => await myTask; 
      Console.ReadLine(); 
     } 
0

Il percorso solito prendo è quello di avere il metodo Main invocare un metodo Run() che restituisce un compito, e .Wait() su Task da completare.

class Program 
{ 
    public static async Task<HttpResponseMessage> CallAsyncMethod() 
    { 
     Console.WriteLine("Calling Youtube"); 
     HttpClient client = new HttpClient(); 
     var response = await client.GetAsync("https://www.youtube.com/watch?v=_OBlgSz8sSM"); 
     Console.WriteLine("Got Response from youtube"); 
     return response; 
    } 

    private static async Task Run() 
    { 
     HttpResponseMessage response = await CallAsyncMethod(); 
     Console.ReadLine(); 
    } 

    static void Main(string[] args) 
    { 
     Run().Wait(); 
    } 
} 

Ciò consente di eseguire il resto dell'app Console con supporto asincrono/Attendi completo. Poiché non esiste alcun thread UI in un'app console, non si corre il rischio di deadlocking con l'utilizzo di .Wait().