Track progress when using TPL's Parallel.ForEach

后端 未结 3 1663
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 11:36

What is the best way way to track progress in the following

long total = Products.LongCount();
long current = 0;
double Progress = 0.0;

Parallel.ForEach(Produc         


        
3条回答
  •  囚心锁ツ
    2021-02-07 12:13

    Since you are just doing a few quick calculations, ensure atomicity by locking on an appropriate object:

    long total = Products.LongCount();
    long current = 0;
    double Progress = 0.0;
    var lockTarget = new object();
    
    Parallel.ForEach(Products, product =>
    {
        try
        {
            var price = GetPrice(SystemAccount, product);
            SavePrice(product,price);
        }
        finally
        {
            lock (lockTarget) {
                Progress = ++this.current / total;
            }
        }});
    

提交回复
热议问题