简体   繁体   中英

How can I simplify this method

In this question I asked how to make a utility method I use awaitable. The answer to my question is this:

    public async Task<TResult> TryAsync<TResult>(Func<IDataServices, Task<TResult>> method)
    {
        using (IDataServices client = GetClient())
        {
            return await method(client);
        }
    }

The above is called like this:

Model m = await ClientResolver.TryAsync(async x => await x.GetModelByIDAsync(modelID));

Just looking at this contraption makes me wonder how it could possibly be efficient. I am awaiting three times here to save myself the trouble of writing a using statement. Is there a better way, perhaps passing IAwaitable? I use this construct quite frequently so I think a bit of optimization will go a long way. I am far down the road in using async await in my app and I'm really starting to think the tail is wagging the dog. But that is a story for another day.

You should be able to get away with just

Model m = await ClientResolver.TryAsync(x => x.GetModelByIDAsync(modelID));

Your TryAsync method already has await in it. I think if you wanted to optimize it you need to profile it and see where the problems are. One possible optimization might be to reuse the client across a class.

You can also avoid switching to the main context by using ConfigureAwait(false) in TryAsync which can help but the performance gain will be very minor.

public async Task<TResult> TryAsync<TResult>(Func<IDataServices, Task<TResult>> method)
{
    using (IDataServices client = GetClient())
    {
        return await method(client).ConfigureAwait(false);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM