异步填充C#字典

5

我正在使用下面的代码循环遍历合同列表并获取每个合同的费率列表。然后将结果存储在字典中。

/// <summary>
/// Get the Rates for the Job keyed to the id of the Organisation
/// </summary>
async Task<Dictionary<int, IReadOnlyList<Rate>>> GetRatesAsync(int jobId)
{
    var jobContracts = await _contractClient.GetJobContractsByJobAsync(jobId);
    var result = new Dictionary<int, IReadOnlyList<Rate>>();
    foreach (var jobContract in jobContracts)
    {
        result.Add(jobContract.Contract.Organisation.Id, await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));
    }
    return result;
}

Resharper提醒我,“循环可以转换为LINQ表达式”。然而,Resharper自动生成的修复程序(如下所示)无法编译。
return jobContracts.ToDictionary(jobContract => jobContract.Contract.Organisation.Id, jobContract => await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));

然后

错误是The await operator can only be used within an async lamba expression。所以加入一个async,并将其更改为以下内容:

return jobContracts.ToDictionary(jobContract => jobContract.Contract.Organisation.Id, async jobContract => await _contractClient.GetContractRatesByContractAsync(jobContract.Contract.Id));

然后

现在出现了错误:无法隐式转换类型 'System.Collections.Generic.Dictionary<int, System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Rate>>>' 为 'System.Collections.Generic.Dictionary<int, System.Collections.Generic.IReadOnlyList<Rate>>',它要求我将签名更改为:

async Task<Dictionary<int, Task<IReadOnlyList<Rate>>>> GetContractRatesAsync()

然后

最终更改现在已经编译通过,但是我的所有调用方法都期望等待Dictionary<int, IReadOnlyList<Rate>>类型的任务,而不是Dictionary<int, Task<IReadOnlyList<Rate>>

有没有一种方法可以等待此任务并将其转换为Dictionary<int, IReadOnlyList<Rate>>?或者其他异步获取数据的方法?


3
我会坚持你的第一种方法 - 如果你需要在多个位置使用,可以编写自己的扩展方法。不过,你可能想要使用ConfigureAwait(false)。 - Jon Skeet
@JonSkeet同意-我暂时不会改变它。我只是想检查一下是否有什么明显的遗漏。我将在Resharper中更改此代码检查的严重级别,从建议更改为提示,以便它停止打扰我。 - JumpingJezza
@JumpingJezza 更好的做法是将此问题报告给JetBrains - svick
1个回答

3
实际上,通用方法可能会非常有趣,所以我将发布一个解决方案。如果您愿意并且应用程序域允许,则可以解决您的初始实现存在的性能问题。
如果您想异步向字典中添加项目,则可能希望允许这些异步项并行运行。您需要从接受键和值的可枚举方法开始。值应该是生成任务的函数,而不是任务本身。这样,您就不会同时运行所有任务。
然后,您可以使用信号量来控制同时启动的任务数量。下面还有一个备用函数,当您希望所有任务同时启动时可以使用它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace _43909210
{
    public static class EnumerableExtensions
    {
        private static async Task<Dictionary<TKey, TValue>> ToDictionary<TKey,TValue>
            (this IEnumerable<(TKey key, Func<Task<TValue>> valueTask)> source)
        {

            var results = await Task.WhenAll
                ( source.Select( async e => (  key: e.key, value:await e.valueTask() ) ) );

            return results.ToDictionary(v=>v.key, v=>v.value);
        }

        public class ActionDisposable : IDisposable
        {
            private readonly Action _Action;
            public ActionDisposable(Action action) => _Action = action;
            public void Dispose() => _Action();
        }

        public static async Task<IDisposable> Enter(this SemaphoreSlim s)
        {
            await s.WaitAsync();
            return new ActionDisposable( () => s.Release() );
        }


        /// <summary>
        /// Generate a dictionary asynchronously with up to 'n' tasks running in parallel.
        /// If n = 0 then there is no limit set and all tasks are started together.
        /// </summary>
        /// <returns></returns>
        public static async Task<Dictionary<TKey, TValue>> ToDictionaryParallel<TKey,TValue>
            ( this IEnumerable<(TKey key, Func<Task<TValue>> valueTaskFactory)> source
            , int n = 0
            )
        {
            // Delegate to the non limiting case where 
            if (n <= 0)
                return await ToDictionary( source );

            // Set up the parallel limiting semaphore
            using (var pLimit = new SemaphoreSlim( n ))
            {
                var dict = new Dictionary<TKey, TValue>();

                // Local function to start the task and
                // block (asynchronously ) when too many
                // tasks are running
                async Task
                    Run((TKey key, Func<Task<TValue>> valueTask) o)
                {
                    // async block if the parallel limit is reached
                    using (await pLimit.Enter())
                    {
                        dict.Add(o.key, await o.valueTask());
                    }
                }

                // Proceed to start the tasks
                foreach (var task in source.Select( Run ))
                    await task;

                // Wait for all tasks to finish
                await pLimit.WaitAsync();
                return dict;
            }

        }
    }

}

我在方法参数上遇到了编译错误,错误信息为“非泛型类型'IEnumerable'不能与类型参数一起使用”? - JumpingJezza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接