Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Func delegate with Async method

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(); } 
like image 955
maxspan Avatar asked May 17 '16 15:05

maxspan


People also ask

Can delegate be async?

Delegates enable you to call a synchronous method in an asynchronous manner.

What happens when you call async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Can async method have multiple awaits?

For more information, I have an async / await intro on my blog. So additionally, if a method with multiple awaits is called by a caller, the responsibility for finishing every statement of that method is with the caller.


1 Answers

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; 
like image 159
spender Avatar answered Oct 10 '22 19:10

spender