使用Func委托与异步方法
问题描述:
我想在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();
}
答
由于错误说,异步方法返回Task
,Task<T>
或void
。因此,为了得到这个工作,你可以:
Func<Task<HttpResponseMessage>> myFun = async() => await myTask;
+1
请注意,当用户按下某个键时,可能无法完成异步操作,而Console.ReadLine()完成。在异步操作完成之前,应用程序可能会终止,除非您在“任务”上显式地“等待”。 –
答
代码修复,如:
static void Main(string[] args)
{
Program p = new Program();
Task<HttpResponseMessage> myTask = p.CallAsyncMethod();
Func<Task<HttpResponseMessage>> myFun = async() => await myTask;
Console.ReadLine();
}
答
我通常采取的路径是有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()
时不会出现死锁的风险。
我有关于[异步委托类型](http://blog.stephencleary.com/2014/02/synchronous-and-asynchronous-delegate.html)的博客文章,您可能会发现有帮助。 –