Track progress when using TPL's Parallel.ForEach

后端 未结 3 1670
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  旧时难觅i
    2021-02-07 12:06

    A solution without using any blocking in the body:

    long total = Products.LongCount();
    BlockingCollection states = new BlockingCollection();
    
    Parallel.ForEach(Products, () =>
    {
        MyState myState = new MyState();
        states.Add(myState);
        return myState;
    },
    (i, state, arg3, myState) =>
    {
        try
        {
            var price = GetPrice(SystemAccount, product);
            SavePrice(product,price);
        }
        finally
        {
            myState.value++;
            return myState;
        }
    },
    i => { }
    );
    

    Then, to access the current progress:

    (float)states.Sum(state => state.value) / total
    

提交回复
热议问题