0

我正在粘贴 4 个代码片段,其中尝试使用以下 API 进行并行化:

Parallel.ForEach
Parallel.Invoke
Task.Run
Task.Factory.StartNew

问题尝试并行化,使得有两个 for 循环,内部和外部,并且对于外部循环的每次执行,内部循环中的所有内容都应该在 Parallel 中执行。

我能够让它工作,Parallel.ForEach而所有其他的都会导致内部计数器的异常,该值超过了数组索引,而在我看来,情况不应该如此。索引也错过了一个更高的值,例如,当索引的大小为 500 时,它会尝试访问值 500,而理想情况下它应该停止在 499。我错过了什么吗?以下是代码片段,请看一下:

Parallel.ForEach(工作)

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace TestThreads
{    
    class Elements
    {
        public int innerValue;
        public int outerValue;

        public Elements(int innerValue, int outerValue)
        {
            this.innerValue = innerValue;
            this.outerValue = outerValue;
        }
    }

    class Program
    {
        private static int threadingCounter = 0;
        private static int innerCounter = 500;
        private static int outerCounter = 1000;
        private static int[,] inOut;
        private static int hitCount = 0;
        private static int exceptionCount = 0;
        private static List<int> innerCount = new List<int>();



        static void Main(string[] args)
        {
            inOut = new int[innerCounter, outerCounter];
            Program myProgram = new Program();

            for (int iCount = 0; iCount < innerCounter; iCount++)
                innerCount.Add(iCount);

            try
            {
                for (int outer = 0; outer < outerCounter; outer++)
                {
                    Parallel.ForEach<int>(innerCount, inner =>
                    {
                        myProgram.ThreadCall(new Elements(inner,outer));
                    }
                    );

                    Console.WriteLine("Main Thread Released Post Wait ...");
                    Console.WriteLine("Hit Count :: " + hitCount);
                    Console.WriteLine("Exception Count :: " + exceptionCount);

                    if (threadingCounter != 0)
                        Console.WriteLine("Threading Counter post Inner Loop :: " + threadingCounter);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception :: " + ex.Message);
            }
            finally
            {                
                if (innerCount != null)
                    innerCount = null;

            }
        }


        public void ThreadCall(object state)
        {
            try
            {
                Interlocked.Increment(ref hitCount);

                Elements localElement = (Elements)state;
                int localInner = localElement.innerValue;
                int localOuter = localElement.outerValue;
                int finalValue = inOut[localInner, localOuter];
            }
            catch (Exception ex)
            {               
                Console.WriteLine("Exception :: " + ex.Message);
            }
        }
    }
}

Parallel.Invoke(数组超出索引值失败,尝试获取内部索引 - 500)

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace TestThreads
{
    /// <summary>
    /// 
    /// </summary>
    class Elements
    {
        public int innerValue;
        public int outerValue;

        public Elements(int innerValue, int outerValue)
        {
            this.innerValue = innerValue;
            this.outerValue = outerValue;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    class Program
    {
        private static int innerCounter = 500;
        private static int outerCounter = 1000;
        private static int[,] inOut;
        private static int hitCount = 0;
        private static int exceptionCount = 0;

        private static List<Action> alSync = new List<Action>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            inOut = new int[innerCounter, outerCounter];
            Program myProgram = new Program();

            try
            {
                for (int outer = 0; outer < outerCounter; outer++)
                {

                    for (int inner = 0; inner < innerCounter; inner++)
                        alSync.Add(() => myProgram.ThreadCall(new Elements(inner, outer)));

                    Parallel.Invoke(alSync.ToArray());                            
                    alSync.Clear();

                    Console.WriteLine("Main Thread Released Post Wait ...");
                    Console.WriteLine("Hit Count :: " + hitCount);
                    Console.WriteLine("Exception Count :: " + exceptionCount);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception :: " + ex.Message);
            }
            finally
            {
                if (alSync != null)
                    alSync = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        public void ThreadCall(object state)
        {
            try
            {
                Interlocked.Increment(ref hitCount);
                Elements localElement = (Elements)state;
                int localInner = localElement.innerValue;
                int localOuter = localElement.outerValue;
                int finalValue = inOut[localInner, localOuter];
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref exceptionCount);
                Console.WriteLine("Exception :: " + ex.Message);
            }

        }
    }
}

Task.Run(数组超出索引值失败,尝试获取内部索引 - 500)

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace TestThreads
{
    /// <summary>
    /// 
    /// </summary>
    class Elements
    {
        public int innerValue;
        public int outerValue;

        public Elements(int innerValue, int outerValue)
        {
            this.innerValue = innerValue;
            this.outerValue = outerValue;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    class Program
    {
        private static int innerCounter = 500;
        private static int outerCounter = 1000;
        private static int[,] inOut;
        private static int hitCount = 0;
        private static int exceptionCount = 0;

        private static List<Task> tlSync = new List<Task>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            inOut = new int[innerCounter, outerCounter];
            Program myProgram = new Program();

            try
            {
                for (int outer = 0; outer < outerCounter; outer++)
                {                  

                    for (int inner = 0; inner < innerCounter; inner++)
                        tlSync.Add(Task.Run(() => myProgram.ThreadCall(new Elements(inner, outer))));

                    Task.WaitAll(tlSync.ToArray());
                    tlSync.Clear();

                    Console.WriteLine("Main Thread Released Post Wait ...");
                    Console.WriteLine("Hit Count :: " + hitCount);
                    Console.WriteLine("Exception Count :: " + exceptionCount);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception :: " + ex.Message);
            }
            finally
            {               
                if (tlSync != null)
                    tlSync = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        public void ThreadCall(object state)
        {
            try
            {
                Interlocked.Increment(ref hitCount);
                Elements localElement = (Elements)state;
                int localInner = localElement.innerValue;
                int localOuter = localElement.outerValue;
                int finalValue = inOut[localInner, localOuter];
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref exceptionCount);
                Console.WriteLine("Exception :: " + ex.Message);
            }           

        }
    }
}

Task.Factory.StartNew(数组超出索引值失败,尝试获取内部索引 - 500)

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace TestThreads
{
    /// <summary>
    /// 
    /// </summary>
    class Elements
    {
        public int innerValue;
        public int outerValue;

        public Elements(int innerValue, int outerValue)
        {
            this.innerValue = innerValue;
            this.outerValue = outerValue;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    class Program
    {
        private static int innerCounter = 500;
        private static int outerCounter = 1000;
        private static int[,] inOut;
        private static int hitCount = 0;
        private static int exceptionCount = 0;

        private static List<Task> tlSync = new List<Task>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            inOut = new int[innerCounter, outerCounter];
            Program myProgram = new Program();

            try
            {
                for (int outer = 0; outer < outerCounter; outer++)
                {

                    for (int inner = 0; inner < innerCounter; inner++)
                        tlSync.Add(Task.Factory.StartNew(() =>  
myProgram.ThreadCall(new Elements(inner, outer))));

                    Task.WaitAll(tlSync.ToArray());
                    tlSync.Clear();

                    Console.WriteLine("Main Thread Released Post Wait ...");
                    Console.WriteLine("Hit Count :: " + hitCount);
                    Console.WriteLine("Exception Count :: " + exceptionCount);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception :: " + ex.Message);
            }
            finally
            {
                if (tlSync != null)
                    tlSync = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        public void ThreadCall(object state)
        {
            try
            {
                Interlocked.Increment(ref hitCount);
                Elements localElement = (Elements)state;
                int localInner = localElement.innerValue;
                int localOuter = localElement.outerValue;
                int finalValue = inOut[localInner, localOuter];
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref exceptionCount);
                Console.WriteLine("Exception :: " + ex.Message);
            }

        }
    }
}
4

1 回答 1

0

不确定 tlSync 的用途是什么,我不明白您为什么要将任务推送到通用列表。

如果你想做一些事情并更新用户界面,你可以从我曾经写过的表单程序中使用的这个功能中获得灵感

var ui = TaskScheduler.FromCurrentSynchronizationContext();
someList
    .ForEach(f => Task.Factory.StartNew(() =>
    {
        // do stuff
    })
    .ContinueWith(task =>
    {
        if (task.IsCompleted)
        {
            // update UI
            // called after each task above completes
        }
    }, ui));

或者您可能有内部/外部的封闭问题,您可以尝试更改此代码

for (int inner = 0; inner < innerCounter; inner++)
    tlSync.Add(Task.Factory.StartNew(() => myProgram.ThreadCall(new Elements(inner, outer))));

对此

for (int inner = 0; inner < innerCounter; inner++) {
    var nInner = inner;
    var nOuter = outer;
    tlSync.Add(Task.Factory.StartNew(() => myProgram.ThreadCall(new Elements(nInner, nOuter))));    
}
于 2013-07-16T22:22:26.770 回答