在Parallel.ForEach循环中,我想增加一个变量,但Interlock.Increment似乎不起作用

时间:2019-05-02 03:16:32

标签: c# parallel.foreach interlocked

我的过程花费很长时间,因此我想将其分解为线程。我的线程方法可以与Parallel.ForEach一起很好地工作,只是我想通知用户到目前为止我们已经处理了多少可变数量的项目。

这是我在做什么的一个例子。

namespace TestingThreading
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private int _idCounter;
        public int IdCounter
        {
            get { return _idCounter; }
            set
            {
                if (value != _idCounter)
                {
                    _idCounter = value;
                    OnPropertyChanged("IdCounter");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string name)
        {
            var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            Counter.SetBinding(ContentProperty, new Binding("IdCounter"));
            DataContext = this;
            IdCounter = 0;
        }

        //random wait as a stand in for a variable length task
        private void GetWait()
        {
            Random random = new Random();
            int w = random.Next(3, 15);
            System.Threading.Thread.Sleep(100 * w);
        }

        private async void CreateClientsButton_Click(object sender, RoutedEventArgs e)
        {   
            //setup my a list of strings to iterate through 
            List<String> DeviceList = new List<string>();
            for (int i = 0; i < 150; i++)
            {
                string ThisClient = "Fox" + i;
                DeviceList.Add(ThisClient);

            }

            var myTask = Task.Run(() =>
            {
                Parallel.ForEach(DeviceList, new ParallelOptions { MaxDegreeOfParallelism = 15 }, device =>
                {
                    GetWait();
                    IdCounter++;
                    // both below give compiler errors
                    //System.Threading.Interlocked.Add(ref IdCounter, 1);
                    //var c = Interlocked.Increment(ref DeviceCounter);
                });
            });

            await myTask;

        }

    }
}

绑定到UI是可行的,但是我很确定我实际上并未将变量递增多少。例如,它将运行150次迭代,但是经过多次尝试,我再也没有见过计数器值高于146,这使我相信两个线程尝试同时更新变量时会出现竞争。

这不是世界末日,但是我很乐意以“正确的方式”做这件事,我的研究使我走向Interlock.IncrementInterlock.Add,但是当我尝试增加我的这些变量之一,我得到这个错误:

  

属性或索引器可能无法作为out或ref参数传递

1 个答案:

答案 0 :(得分:1)

我强烈建议您使用IProgress<T>来更新UI。使用“有状态”进度(即“增量”)而不是“无状态”进度(即“第13项已完成”)是不寻常的,但这是可行的。

请注意,Progress<T>负责与UI线程同步,因此可以为您解决竞争条件。

var progress = new Progress<int>(_ => IdCounter++) as IProgress<int>;
var myTask = Task.Run(() =>
{
  Parallel.ForEach(DeviceList, new ParallelOptions { MaxDegreeOfParallelism = 15 }, device =>
  {
    GetWait();
    progress.Report(0);
  });
});