TPL BufferBlock.ReceiveAsync两次接收同一项目

时间:2019-03-15 12:56:35

标签: c# task-parallel-library azure-service-fabric tpl-dataflow bufferblock

我有这样的BufferBlock设置。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace NG_20.Controllers
{
    [Route("api/[controller]/[action]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> WeatherForecasts(int startDateIndex = 0)
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index + startDateIndex).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        [HttpPost]
        public object Post([FromBody] object weatherForecast)
        {
            var forecast = JObject.Parse(weatherForecast.ToString()).ToObject<WeatherForecast>();
            var x = forecast.DateFormatted;
            return weatherForecast;
        }



        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

让多个使用者从不同的线程中调用“ FetchWork”功能

_inputQueue = new BufferBlock<WorkItem>(new DataflowBlockOptions
{
    BoundedCapacity = 1,
    CancellationToken = cancellationToken,
    EnsureOrdered = true
});

有时,同一工作项最终会出现在多个使用者中! InputQueue中的工作项数量越多,GetWork中收到重复项的机会就越多。我的理解是,通过ReceiveAsync提取的项是原子的,一旦读取了一项,就不会再次读取。这不在这里发生。 40个并行的消费者致电GetWork。

1 个答案:

答案 0 :(得分:1)

这似乎是服务结构问题。 BufferBlock仅使该项目出队一次。生产者[分区数为5的服务结构状态服务实例]在不同的分区中两次接收同一项目。必须对此进行调查。