将Func委托与Async方法一起使用 [英] Using Func delegate with Async method

查看:485
本文介绍了将Func委托与Async方法一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Func与异步方法一起使用.而且我遇到了错误.

I am trying to use Func with Async Method. And I am getting an error.

无法将异步lambda表达式转换为委托类型'Func<HttpResponseMesage>'.异步lambda表达式可能返回void,Task或Task<T>,而这些都不可转换为'Func<HttpResponseMesage>'.

Cannot convert async lambda expression to delegate type 'Func<HttpResponseMesage>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to '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();
}

推荐答案

如错误所示,异步方法返回TaskTask<T>void.因此,要使其正常工作,您可以:

As the error says, async methods return Task,Task<T> or void. So to get this to work you can:

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

这篇关于将Func委托与Async方法一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆