Reputation: 33079
I have an extension method called Use
that takes an Action
as an argument:
IEnumerable<User> users;
service.Use(client => {
users = client.GetUsers();
});
// users has a value now
When I go to use the async
version of GetUsers()
:
IEnumerable<User> users;
service.Use(async (client) => {
users = await client.GetUsersAsync();
});
// users is null
...then the line // users is null
is reached before await client.GetUsersAsync()
returns a result.
How do I make sure that if my Action
's body includes any await
keyword, execution doesn't continue past Use()
before the await
in the Action
's body is finished?
Note that I can't change the signature of Use()
. The Action
argument cannot be changed to a Func
.
Upvotes: 0
Views: 506
Reputation: 17855
You will need to change the signature of Use
if you want the async lambda to be awaited:
Task Use(Func<Task> action)
{
await action();
}
and then await it:
await service.Use(async (client) => {
users = await client.GetUsersAsync();
});
If you can't do that, your only option is to wait for the task to complete instead of awaiting it (which defeats the purpose of using the async method in the first place):
service.Use((client) => {
users = client.GetUsersAsync().Result;
});
Upvotes: 1