user2450759
user2450759

Reputation: 105

Refactoring out part of async method to lambda

I'm fairly new to the concept of async and await. Right now I've got something like this:

public async void DoSomething()
{
    using (var obj = new SomeClass())
    {
        await obj.SomeAction();
    }

    Done = true;
}

But as the creation and management of the obj object is becoming more complex, I would like to refactor it to something like this:

public async void DoSomething()
{
    Manager.Execute(obj =>
    {
        await obj.SomeAction();
    });

    Done = true;
}

But the above code won't compile. It surely lacks some async or await keywords here or there. I also don't know how to write the Execute() method. Can you help?

Upvotes: 0

Views: 100

Answers (1)

Nuffin
Nuffin

Reputation: 3972

First, to use await in lambdas, you have to decorate them with the async modifier, just like a method:

Func<Task<Foo>> asyncFooFactory = async () => await whatever;

And the Execute method would then look like this:

// instead of Task, you could use void, but then you can't await its completion,
// which could get handy later, depending on your use case
public static async Task Execute(Func<YourClass, Task> externalStuff)
{
    using (var obj = new YourClass()) // replace with your own initializer code
    {
        await externalStuff(obj);
    }
}

Upvotes: 1

Related Questions