Cannot convert lambda expression to type "..." because it is not a delegate type
To add to Yuval's useful answer, if you just want to await an inline function, then the magic syntax is:
await ((Func<Task>)(async () =>
{
//async function code
}
))();
Note the extra brackets on the end to call the lambda immediately after declaration. Obviously if your function returns a type, then it would be Func<Task<Whatever>>
Useful if you're using Task.WhenAny()
for example to await both an inline function and a timeout task.
If you want an Anonymous Method, you'll have to declare one which returns a Task<Session>
as it is marked with the async
modifier, hence must return a void
(only for async event handlers), Task
or Task<T>
:
Func<Task<Session>> anonFunction = async () => await fileService.ReadJsonAsync();
If all you do is run ReadJsonAsync
, you may also save yourself the state machine generation like so:
Func<Task<Session>> anonFunction = fileService.ReadJsonAsync;
Then you can await
on it higher up the call stack:
Func<Task<Session>> anonFunction = fileService.ReadJsonAsync;
await anonFunction();