简体   繁体   English

我该如何简化这种方法

[英]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? 有没有更好的方法,也许通过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. 你的TryAsync方法已经await了。 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. 您还可以通过在TryAsync使用ConfigureAwait(false)来避免切换到主上下文,这可能有所帮助,但性能提升将非常小。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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