Using Func delegate with Async method

maxspan picture maxspan · May 17, 2016 · Viewed 72.3k times · Source

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

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>'.

below is my Code:

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

Answer

spender picture spender · May 17, 2016

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;