0

Хочу сделать расчет числа Пи через одну кнопку, но есть проблема в том что метод вызывается сразу после запуска потоков. Как сделать так чтобы потоки закончили свою работу и только тогда вызвался метод?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Monte_Carlo
{
    delegate void InvokeDelegate(int progress);

    public partial class Form1 : Form
    {

        static List<double> n_circle_List = new List<double>();
        private void Method_Monte_Karlo()
        {
            double _num;
            _num = int.Parse(textBox2.Text)/4;
            int n_point = (int)_num;
            double n_circle = 0;
            double n_point_count = n_point;
            double count= n_point;
            int progress;
            Random r = new Random();
            for (int i = 0; i <= n_point; i++)
            {
                if (IsPointInCircle(1.0, r.NextDouble(), r.NextDouble()))
                {
                    n_circle++;
                }
                progress = (int)((i / (count)) * 100);
                this.Invoke(new InvokeDelegate(updateChart), progress);
                Thread.Sleep(1);
                n_point_count++;
            }
            n_circle_List.Add(n_circle);
        }
        private void updateChart(int progress)
        {

            progressBar1.Value = progress;
            label1.Text = progress + "%";
            Thread.Sleep(1);

            //if (progress == 100)
            //{
            //    PI();
            //}
        }
        private void PI()
        {
            int _num;
            double pi = 0;
            double j = 0;
            _num = int.Parse(textBox2.Text);
            if (progressBar1.Value == 100)
            {
                for (int i = 0; i < n_circle_List.Count; i++)
                {
                    j += n_circle_List[i];
                }
                pi = 4 * j / _num;
                textBox6.Text = pi.ToString();
                n_circle_List.Clear();
                // progressBar1.Value = 0;
                label1.Text = "0%";
            }
        }
            static bool IsPointInCircle(double R, double x, double y)
        {
            return ((x * x + y * y) <= R * R);
        }
        static void Threads(int numThreads, int num)
        {
            ThreadPool.SetMaxThreads(numThreads, 0);
            for (int i = 0; i < numThreads; i++)
            {
               // ThreadPool.QueueUserWorkItem(new WaitCallback(Method_Monte_Karlo), num);
                Thread.Sleep(20);

            }

        }
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int _num;
            double pi = 0;
            double j = 0;
            _num = int.Parse(textBox2.Text);
            if (progressBar1.Value == 100)
            {
                for (int i = 0; i < n_circle_List.Count; i++)
                {
                    j += n_circle_List[i];
                }
                pi = 4 * j / _num;
                textBox6.Text = pi.ToString();
                n_circle_List.Clear();
                // progressBar1.Value = 0;
            }
            //t.IsBackground = true;
            //t.Start();
            //int numThr;
            //int _num;
            //numThr = int.Parse(textBox1.Text);
            //_num = int.Parse(textBox2.Text); 
            //Threads(numThr, _num);
            //textBox6.Clear();
            //progressBar1.Value = ((int)n_circle_List.Count/numThr)*100;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread t1 = new Thread(new ThreadStart(Method_Monte_Karlo));        
            Thread t2 = new Thread(new ThreadStart(Method_Monte_Karlo));        
            Thread t3 = new Thread(new ThreadStart(Method_Monte_Karlo));     
            Thread t4 = new Thread(new ThreadStart(PI));
            t1.IsBackground = true;
            t1.Start();
            t2.IsBackground = true;
            t2.Start();
            t3.IsBackground = true;
            t3.Start();
            t4.IsBackground = true;
            t4.Start(); 
            if (progressBar1.Value == 100)
            {
                PI();
            }

        }
    }
}
0

1 ответ 1

2

Использовать Task вместо Thread, асинхронный обработчик события, добавить таски в список и использовать await Task.WhenAll()

private async void button2_Click(object sender, EventArgs e)
{
    List<Task> tasks = new List<Task>();
    tasks.Add(Task.Run(Method_Monte_Karlo));
    tasks.Add(Task.Run(Method_Monte_Karlo));
    tasks.Add(Task.Run(Method_Monte_Karlo));     
    tasks.Add(Task.Run(PI));
    await Task.WhenAll(tasks);
    if (progressBar1.Value == 100)
    {
        PI();
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.