gpt4 book ai didi

c# - 将 Func 委托(delegate)与 Async 方法结合使用

转载 作者:IT王子 更新时间:2023-10-29 03:56:20 31 4
gpt4 key购买 nike

我正在尝试将 Func 与异步方法结合使用。我收到一个错误。

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

最佳答案

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

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

关于c# - 将 Func 委托(delegate)与 Async 方法结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280405/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com