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

namespace Threadlokale_Variablen
{
    class MyCollection
    {
        List<int> elements;
        int sum;

        public MyCollection()
        {
            elements = new List<int>();

            // Werte einlesen
            String input = "";
            Console.WriteLine(" Werte eingeben (b zum Beenden): \n");

            while (true)
            {
                Console.Write(" Wert: ");
                input = Console.ReadLine();

                if (input == "b")
                    break;      // Schleife verlassen

                elements.Add(Convert.ToInt32(input));
            }

            Console.WriteLine("\n");
        }

        public double MeanValue()
        {
            Parallel.For<int>(0, elements.Count,
                               () => { return 0; },
                               (n, status, subresult) =>
                               {
                                   Thread.SpinWait(Int32.MaxValue);
                                   subresult = elements[n];
                                   return subresult;
                               },
                               (n) => { Interlocked.Add(ref sum, n); }
            );

            return sum / elements.Count;
        }
    }

    
    class Program
    {
        static void Main(string[] args)
        {
            MyCollection data = new MyCollection();
            Console.WriteLine("\n Mittelwert wird berechnet \n");
            Console.WriteLine("\n Mittelwert: " + data.MeanValue());

            Console.ReadLine();
        }
    }
}
