异步填充c#字典

时间:2017-05-11 07:33:56

标签: c# linq for-loop async-await resharper

我在下面使用此代码循环显示合同列表,并获取每份合约的费率列表。然后它将结果存储在Dictionary中。

/// <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));

然后

错误现在是Cannot implicitly convert type 'System.Collections.Generic.Dictionary<int, System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Rate>>>' to '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>>?或者以其他方式异步获取数据?

1 个答案:

答案 0 :(得分:2)

实际上,通用方法可能非常有趣,所以我会发布一个解决方案。如果您愿意,您的初始实施可能会遇到性能问题,并且您的应用程序域允许它。

如果要异步向项目添加项目,则可能需要允许这些异步项目并行运行。您希望从一个接受可枚举键和值的方法开始。值应该是生成任务而不是任务的函数。这样您就不会立即运行所有任务。

然后使用信号量控制同时启动的任务数。当您对同时开始的所有任务感到满意时,下面还有一个后备功能。

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;
            }

        }
    }

}