使用BlockingCollection在Producer / Consumer模式async中添加项目

时间:2017-11-15 16:51:34

标签: c# asynchronous task producer-consumer

我关注BlockingCollection foreach以实现生产者/消费者模式,但仍无法让我的任务在生产者端并行执行。

问题是我的PropertyLien<T>块正在按顺序执行。从this guide开始,我了解到我必须将Task作为// PropertyLien<T> is a class that models an asset (house/building/etc) var googleAddresses = new BlockingCollection<Tuple<PropertyLien<string>, IEnumerable<GoogleAddress>>>() // Consumer Threads var consumer = Task.Run(() => { while(!googleAddresses.IsCompleted) { var adr = googleAddresses.Take(); // Do work } Console.WriteLine("No more addresses to process"); }); // Producer Threads var producer = Task.Factory.StartNew(async () => { // TODO: PROBLEM here, this is executing synchronously foreach(PropertyLien<string> property in properties) { try { // See: https://www.nuget.org/packages/Geocoding.net/ await geocoder.GeocodeAsync(property.Address) .ContinueWith(task => { var googResults = task.Result; googleAddresses.Add(property, googResults); }); } catch {} } googleAddresses.CompleteAdding(); }); // Need to wait for both tasks to complete. Task.WaitAll(producer, consumer); 项目集合。{{1}}。怎么做的?

{{1}}

1 个答案:

答案 0 :(得分:0)

感谢@Evk,这就是答案:

// Producer Threads
var producer = Task.Factory.StartNew(async () => {
    var tasks = properties.Select(property => {
        return geocoder.GeocodeAsync(property.Address)
            .ContinueWith(task => {
                // Do work
            });
    });

    await Task.WhenAll(tasks);
    googleAddresses.CompleteAdding();
});