2016-05-17 116 views
12

我想在Async方法中使用Func。我收到一个错误。使用Func委托与异步方法

无法将异步lambda表达式转换为委托类型'Func<HttpResponseMesage>'。异步lambda表达式可能返回void,Task或Task<T>,其中没有一个可转换为'Func<HttpResponseMesage>'。下面

是我的代码:

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

我有关于[异步委托类型](http://blog.stephencleary.com/2014/02/synchronous-and-asynchronous-delegate.html)的博客文章,您可能会发现有帮助。 –

回答

21

由于错误说,异步方法返回TaskTask<T>void。因此,为了得到这个工作,你可以:

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

请注意,当用户按下某个键时,可能无法完成异步操作,而Console.ReadLine()完成。在异步操作完成之前,应用程序可能会终止,除非您在“任务”上显式地“等待”。 –

1

代码修复,如:

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

我通常采取的路径是有Main方法调用Run()方法返回一个任务,并.Wait()Task上完成。

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(); 
    } 
} 

这使您的其他控制台应用程序可以在完全异步/等待支持下运行。由于控制台应用程序中没有任何UI线程,因此使用.Wait()时不会出现死锁的风险。