コード例 #1
0
        private static void Ex06()
        {
            int sum = 0;

            EventWaitHandle[] events = new EventWaitHandle[] {
                new AutoResetEvent(false),
                new AutoResetEvent(false),
                new AutoResetEvent(false)
            };

            new Thread(() => {
                int result = SlowMath.SlowSquare04(5);
                Interlocked.Add(ref sum, result);
                Console.WriteLine(result);
                events[0].Set();
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(3);
                Interlocked.Add(ref sum, result);
                Console.WriteLine(result);
                events[1].Set();
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(4);
                Interlocked.Add(ref sum, result);
                Console.WriteLine(result);
                events[2].Set();
            }).Start();

            EventWaitHandle.WaitAll(events);
            Console.WriteLine($"The sum is {sum}");
        }
コード例 #2
0
        private void btnTasksResult_Click(object sender, EventArgs e)
        {
            //Tasks
            //synchronizationcontext
            //interlocked

            int sum = 0;
            SynchronizationContext ctx = SynchronizationContext.Current;

            int[]        values = new int[] { int.Parse(textBox1.Text), int.Parse(textBox2.Text), int.Parse(textBox3.Text) };
            Label[]      labels = new Label[] { label1, label2, label3 };
            Task <int>[] tasks  = new Task <int> [3];
            Task.Run(() => {
                for (int i = 0; i < 3; i++)
                {
                    tasks[i] = Task.Factory.StartNew(local_i =>
                    {
                        int result = SlowMath.SlowSquare04(values[(int)local_i]);
                        ctx.Post(res => {
                            labels[(int)local_i].Text = res.ToString();
                        }, result);
                        return(result);
                    }, i);
                }
                sum = tasks[0].Result + tasks[1].Result + tasks[2].Result;
                ctx.Post(o => {
                    label4.Text = sum.ToString();
                }, null);
            });
        }
コード例 #3
0
        private static void Ex05()
        {
            int    sum       = 0;
            object lockOnSum = new object();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(5);
                lock (lockOnSum) {
                    sum += result;
                }
                Console.WriteLine(result);
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(3);
                lock (lockOnSum) {
                    sum += result;
                }
                Console.WriteLine(result);
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(4);
                lock (lockOnSum) {
                    sum += result;
                }
                Console.WriteLine(result);
            }).Start();
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: MaxMommersteeg/.NET-Minor
        private void btnSquare_Click(object sender, EventArgs e)
        {
            int invoer = int.Parse(txtInput.Text);

            SlowMath     math = new SlowMath();
            IAsyncResult ar   = math.BeginSquare(invoer, SquareCalculated, math);
        }
コード例 #5
0
        private void btnParallelFor_Click(object sender, EventArgs e)
        {
            //threadpool
            //parallel for
            //synchronizationcontext
            //interlocked

            int sum = 0;
            SynchronizationContext ctx = SynchronizationContext.Current;

            int[]   values = new int[] { int.Parse(textBox1.Text), int.Parse(textBox2.Text), int.Parse(textBox3.Text) };
            Label[] labels = new Label[] { label1, label2, label3 };

            ThreadPool.QueueUserWorkItem(_ => {
                Parallel.For(0, 3, (i) => {
                    int result = SlowMath.SlowSquare04(values[i]);
                    Interlocked.Add(ref sum, result);

                    ctx.Post(res => {
                        labels[i].Text = res.ToString();
                    }, result);
                });

                ctx.Post(o => {
                    label4.Text = sum.ToString();
                }, null);
            });
        }
コード例 #6
0
        private async void btnSumOfSquaresAsync_Click(object sender, EventArgs e)
        {
            _startDateTime = DateTime.Now;

            if (!ValidateInputControls())
            {
                return;
            }

            SlowMath math = new SlowMath();

            Task <int> task1 = math.SquareAsync(_input1);
            Task <int> task2 = math.SquareAsync(_input2);
            Task <int> task3 = math.SquareAsync(_input3);

            //var result = await Task.WhenAll(new List<int> { _input1, _input2, _input3 }.Select(i => math.SquareAsync(i)));

            int result1 = await task1;
            int result2 = await task2;
            int result3 = await task3;

            txtOutput.Text = (result1 + result2 + result3).ToString();

            _endDateTime = DateTime.Now;

            MessageBox.Show(_startDateTime.ToString() + " - " + _endDateTime.ToString());
        }
コード例 #7
0
        private static void Ex07()
        {
            int sum = 0;

            EventWaitHandle[] events = new EventWaitHandle[] {
                new AutoResetEvent(false),
                new AutoResetEvent(false),
                new AutoResetEvent(false)
            };

            int[] values = new int[] { 5, 3, 4 };

            for (int i = 0; i < 3; i++)
            {
                new Thread((myI) => {
                    int result = SlowMath.SlowSquare04(values[(int)myI]);
                    Interlocked.Add(ref sum, result);
                    Console.WriteLine(result);
                    events[(int)myI].Set();
                }).Start(i);
            }

            EventWaitHandle.WaitAll(events);
            Console.WriteLine($"The sum is {sum}");
        }
コード例 #8
0
        private static void Ex03WithSumUpdate()
        {
            SlowMath sm = new SlowMath();

            new Thread(() => sm.SlowSquare03WithSumUpdate(3)).Start();
            new Thread(() => sm.SlowSquare03WithSumUpdate(2)).Start();
            new Thread(() => sm.SlowSquare03WithSumUpdate(4)).Start();
        }
コード例 #9
0
        public static async Task <int> DoWork()
        {
            SlowMath math     = new SlowMath();
            int      kwadraat = await math.SquareAsync(5);

            Console.WriteLine(kwadraat);

            return(kwadraat);
        }
コード例 #10
0
 private void btn1_Click(object sender, EventArgs e)
 {
     intLijst = new List <int>();
     SlowMath     math       = new SlowMath();
     int          invoer1    = int.Parse(txt1.Text);
     int          invoer2    = int.Parse(txt2.Text);
     int          invoer3    = int.Parse(txt3.Text);
     IAsyncResult txt1Result = math.BeginSquare(invoer1, Update, math);
     IAsyncResult txt2Result = math.BeginSquare(invoer2, Update, math);
     IAsyncResult txt3Result = math.BeginSquare(invoer3, Update, math);
 }
コード例 #11
0
ファイル: Form1.cs プロジェクト: MaxMommersteeg/.NET-Minor
        private void SquareCalculated(IAsyncResult ar)
        {
            SlowMath math = (SlowMath)ar.AsyncState;

            int uitvoer = math.EndSquare(ar);

            var somedelegate = (MethodInvoker)(() =>
            {
                txtOutput.Text = uitvoer.ToString();
            });

            Invoke(somedelegate);
        }
コード例 #12
0
        private void CalulateSumSquares2(object invoerObj)
        {
            int[] invoer = (int[])invoerObj;

            SlowMath math = new SlowMath();

            int sum = invoer.Select(n => math.BeginSquare(n, null, null))
                      .ToList()
                      .Select(ar => math.EndSquare(ar))
                      .Sum();

            Invoke(new Action(() => {
                txtUitvoer.Text = sum.ToString();
            }));
        }
コード例 #13
0
        private void Update(IAsyncResult resultaat)
        {
            SlowMath math = (SlowMath)resultaat.AsyncState;

            lock (intLijst){
                intLijst.Add(math.EndSquare(resultaat));
            }
            if (intLijst.Count >= 3)
            {
                int uitvoer = intLijst.Sum();
                Invoke((MethodInvoker)(() =>
                {
                    txtresult.Text = uitvoer.ToString();
                }));
            }
        }
コード例 #14
0
        private async void btnSumOfSquaresAsync_Click(object sender, EventArgs e)
        {
            int[] invoer = new int[3];
            if (int.TryParse(txtInvoer1.Text, out invoer[0]) &&
                int.TryParse(txtInvoer2.Text, out invoer[1]) &&
                int.TryParse(txtInvoer3.Text, out invoer[2]))
            {
                SlowMath math = new SlowMath();

                //var squares1 = await Task.WhenAll(invoer.Select(n => math.SquareAsync(n)));
                var squares2 = await from n in invoer
                               select math.SquareAsync(n);

                txtUitvoer.Text = squares2.Sum().ToString();
            }
        }
コード例 #15
0
        private static void Ex01()
        {
            SlowMath sm = new SlowMath();

            sm.SlowSquare01(4);
            sm.SlowSquare01(5);
            sm.SlowSquare01(3);

            Thread t1 = new Thread(sm.SlowSquare01);
            Thread t2 = new Thread(sm.SlowSquare01);
            Thread t3 = new Thread(sm.SlowSquare01);

            t1.Start(4);
            t2.Start(5);
            t3.Start(3);
        }
コード例 #16
0
        private async void button1_Click(object sender, EventArgs e)
        {
            intLijst = new List <int>();
            SlowMath math    = new SlowMath();
            int      invoer1 = int.Parse(txt1.Text);
            int      invoer2 = int.Parse(txt2.Text);
            int      invoer3 = int.Parse(txt3.Text);

            intLijst.Add(await math.SquareAsync(invoer1));
            intLijst.Add(await math.SquareAsync(invoer2));
            intLijst.Add(await math.SquareAsync(invoer3));

            Invoke((MethodInvoker)(() =>
            {
                txtresult.Text = (intLijst.Sum()).ToString();
            }));
        }
コード例 #17
0
        private static void Ex04()
        {
            new Thread(() => {
                int result = SlowMath.SlowSquare04(5);
                Console.WriteLine(result);
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(3);
                Console.WriteLine(result);
            }).Start();

            new Thread(() => {
                int result = SlowMath.SlowSquare04(4);
                Console.WriteLine(result);
            }).Start();
        }
コード例 #18
0
        private void btnSumOfSquares_Click(object sender, EventArgs e)
        {
            _startDateTime = DateTime.Now;

            if (!ValidateInputControls())
            {
                return;
            }

            _results       = new ConcurrentBag <int>();
            txtOutput.Text = string.Empty;

            SlowMath slowMath = new SlowMath();

            slowMath.BeginSquare(_input1, OnSquareResultReceived, slowMath);
            slowMath.BeginSquare(_input2, OnSquareResultReceived, slowMath);
            slowMath.BeginSquare(_input3, OnSquareResultReceived, slowMath);
        }
コード例 #19
0
        private void OnSquareResultReceived(IAsyncResult asyncResult)
        {
            SlowMath math       = (SlowMath)asyncResult.AsyncState;
            var      tempResult = math.EndSquare(asyncResult);

            _results.Add(tempResult);
            if (_results.Count == 3)
            {
                var updateTxtOutput = (MethodInvoker)(() =>
                {
                    var temp = _results.Sum().ToString();
                    txtOutput.Text = temp;
                });
                Invoke(updateTxtOutput);
                _endDateTime = DateTime.Now;
                MessageBox.Show(_startDateTime.ToString() + " - " + _endDateTime.ToString());
            }
        }
コード例 #20
0
        private void CalulateSumSquares(object invoerObj)
        {
            int[] invoer = (int[])invoerObj;

            SlowMath math = new SlowMath();
            var      ar0  = math.BeginSquare(invoer[0], null, null);
            var      ar1  = math.BeginSquare(invoer[1], null, null);
            var      ar2  = math.BeginSquare(invoer[2], null, null);

            int sum = 0;

            sum += math.EndSquare(ar0);
            sum += math.EndSquare(ar1);
            sum += math.EndSquare(ar2);

            Invoke((MethodInvoker)(() => {
                txtUitvoer.Text = sum.ToString();
            }));
        }
コード例 #21
0
        private void btnTasks_Click(object sender, EventArgs e)
        {
            Task <int> t1 = SlowMath.SlowSquareAsync(int.Parse(textBox1.Text));
            Task <int> t2 = SlowMath.SlowSquareAsync(int.Parse(textBox2.Text));
            Task <int> t3 = SlowMath.SlowSquareAsync(int.Parse(textBox3.Text));

            //t1.ContinueWith(tres => label1.Text = tres.Result.ToString()); //BOOM!

            //SynchronizationContext ctx = SynchronizationContext.Current;
            //t1.ContinueWith(tres => {
            //    ctx.Post(_ => label1.Text = tres.Result.ToString(), null);
            //}); //this works, but we can write less code with the following overload of the ContinueWith:


            t1.ContinueWith(tres => label1.Text = tres.Result.ToString(), TaskScheduler.FromCurrentSynchronizationContext()); //better
            t2.ContinueWith(tres => label2.Text = tres.Result.ToString(), TaskScheduler.FromCurrentSynchronizationContext());
            t3.ContinueWith(tres => label3.Text = tres.Result.ToString(), TaskScheduler.FromCurrentSynchronizationContext());

            Task.WhenAll(t1, t2, t3).ContinueWith(tres => label4.Text = tres.Result.Sum().ToString(), TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #22
0
        private async void btnAsyncAwait01_Click(object sender, EventArgs e)
        {
            // with this solution we don't block the ui,
            // but we don't see the result as soon as possible

            Task <int> t1 = SlowMath.SlowSquareAsync(int.Parse(textBox1.Text));
            Task <int> t2 = SlowMath.SlowSquareAsync(int.Parse(textBox2.Text));
            Task <int> t3 = SlowMath.SlowSquareAsync(int.Parse(textBox3.Text));

            int r1 = await t1;

            label1.Text = r1.ToString();
            int r2 = await t2;

            label2.Text = r2.ToString();
            int r3 = await t3;

            label3.Text = r3.ToString();

            label4.Text = (r1 + r2 + r3).ToString();
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: MaxMommersteeg/.NET-Minor
        static void Main(string[] args)
        {
            int i1 = 5;
            int i2 = 2;
            int i3 = 3;

            var startTime = DateTime.Now.Second;
            var slowMath  = new SlowMath();

            Task <int>[] tasks = new Task <int>[]
            {
                Task <int> .Factory.StartNew(() => r1 = slowMath.SquareAsync(i1).Result),
                Task <int> .Factory.StartNew(() => r2 = slowMath.SquareAsync(i2).Result),
                Task <int> .Factory.StartNew(() => r3 = slowMath.SquareAsync(i3).Result),
            };
            Task.WaitAll(tasks);
            var endTime = DateTime.Now.Second;

            var difference = endTime - startTime;

            Console.WriteLine($"{r1 + r2 + r3} {difference}");
        }
コード例 #24
0
        private static void Ex08()
        {
            int sum = 0;

            CountdownEvent evt = new CountdownEvent(3);

            int[] values = new int[] { 5, 3, 4 };

            for (int i = 0; i < 3; i++)
            {
                new Thread((myI) =>
                {
                    int result = SlowMath.SlowSquare04(values[(int)myI]);
                    Interlocked.Add(ref sum, result);
                    Console.WriteLine(result);
                    evt.Signal();
                }).Start(i);
            }

            evt.Wait();
            Console.WriteLine($"The sum is {sum}");
        }
コード例 #25
0
        private void button1_Click(object sender, EventArgs e)
        {
            //threadpool
            //countdownevent
            //synchronizationcontext
            //interlocked

            int                    sum       = 0;
            CountdownEvent         countdown = new CountdownEvent(3);
            SynchronizationContext ctx       = SynchronizationContext.Current;

            int[]   values = new int[] { int.Parse(textBox1.Text), int.Parse(textBox2.Text), int.Parse(textBox3.Text) };
            Label[] labels = new Label[] { label1, label2, label3 };

            for (int i = 0; i < 3; i++)
            {
                ThreadPool.QueueUserWorkItem((myI) => {
                    int index  = (int)myI;
                    int result = SlowMath.SlowSquare04(values[index]);
                    Interlocked.Add(ref sum, result);

                    countdown.Signal();

                    ctx.Post(res => {
                        labels[index].Text = res.ToString();
                    }, result);
                }, i);
            }

            ThreadPool.QueueUserWorkItem(_ => {
                countdown.Wait();
                ctx.Post(o => {
                    label4.Text = sum.ToString();
                }, null);
            });
        }
コード例 #26
0
 private static void Ex03()
 {
     new Thread(() => SlowMath.SlowSquare03(5)).Start();
     new Thread(() => SlowMath.SlowSquare03(6)).Start();
     new Thread(() => SlowMath.SlowSquare03(7)).Start();
 }