Problems with Threads in Windows Form

2

I'm trying to implement Threads in my algorithm, but when I add and run my software the Windows Form of it hangs and does not take any action, can you see something wrong in the code below? I know there is Async/Await to be used with task , but is it possible to use Threads as I used, in Windows Form ? If not, what would be the best way to add a task pool that would "take" at least 90% of my processor to run the Algorithm?

Thank you in advance!

    GeneticAlgorithm AG = new GeneticAlgorithm();
    List<Thread> threads = new List<Thread>();

    for (i = iTemp; i < evolucoes; i++)
    {
        Thread thread_corrente = new Thread(() =>
        {
            #region
            iTemp++;

            lbEvolucoes.Text = i.ToString();
            lbEvolucoes.Refresh();

            pop = AG.executeGA(pop);

            if (twoOptCheck.Checked)
            {
                if (i == evolucoes - 1)
                    Utils.TwoOpt(pop.getBest());
            }
            pop.getBest().CalcFitness();

            //Limpar o grafico
            zedMedia.GraphPane.CurveList.Clear();
            zedMedia.GraphPane.GraphObjList.Clear();

            double mediaPop = pop.getMediaPop();
            mediaPopulacao.Add(i, mediaPop);

            double bestFitness = pop.getBest().getFitness();

            lbMenorDistancia.Text = bestFitness.ToString("0.0");
            lbMenorDistancia.Refresh();

            LineItem media = paneMedia.AddCurve("Média", mediaPopulacao, Color.Red, SymbolType.None);

            //Print linhas a cada 6 evolucoes
            if (i % 6 == 0 && bestFitness < bestAux)
            {
                bestAux = bestFitness;
                g.Clear(Color.White);
                plotLines(pop, Color.Blue);
                plotPoints();
            }

            zedMedia.AxisChange();
            zedMedia.Invalidate();
            zedMedia.Refresh();
            #endregion
        });

        thread_corrente.Start();
        threads.Add(thread_corrente);
        if (threads.Count >= 10)
        {
            while (!ThreadsTerminaramDeProcesssar(threads))
            {
                Thread.Sleep(5000);
            }

            threads.Clear();
        }
    }

    g.Clear(Color.White);
    plotLines(pop, Color.Blue);
    plotPoints();

    btnExecutar.Enabled = true;
}

Checks if Thread has already processed:

   private bool ThreadsTerminaramDeProcesssar(List<Thread> threads)
    {
        bool TodosTerminaramDeProcessar = true;

        foreach (Thread thread in threads)
        {
            //true => não terminou seu processamento.
            //false => terminou seu processamento.
            if (thread.IsAlive)
                TodosTerminaramDeProcessar = false;
        }

        return TodosTerminaramDeProcessar;
    }
    
asked by anonymous 12.08.2018 / 06:14

0 answers