How to use async / await in methods that return void?

0

I have a problem with my application, where due to the large volume of processing, my Form hangs. During my research I discovered that a async method solves this, but the functions executed on my "execute" button return void, so I can not use await because I do not know when the execution of the function will end (since it does not return a task).

Ah some way to use Thread or Task in this scenario? Unlocking form and splitting processing?

EDIT AFTER SUGGESTIONS:

My for looks like this after the suggestions:

for (i = iTemp; i < evolucoes; i++)
        {
            iTemp++;

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

            await Task.Factory.StartNew(() =>
              {
                  pop = AG.executeGA(pop);
              });


            // pop = AG.executeGA(pop);

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

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

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

            #region Começo do dois opt

            await Task.Factory.StartNew(() =>                 
            {

                var tasks = new List<Task>();
                for (int j = 0; j < 100; j++)
                    tasks.Add(Task.Run(() =>
                    {
                        Utils.TwoOpt(pop.getBest());
                    }));
            });

            #endregion

            lbMenorDistancia.Text = bestFitness.ToString();
            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();
        }

It's this way, is it legal?

    
asked by anonymous 09.08.2018 / 18:21

2 answers

2

A method that returns void can also be asynchronous, so you can also use await inside it.

To make it asynchronous, include the prefix async in your header, see an example:

private async void button1_Click(object sender, EventArgs e)

One way to not make it run at top-level (protected from unobserved exceptions), is to use Task.Factory , see:

private async void button1_Click(object sender, EventArgs e)
{
    await Task.Factory.StartNew(() =>
    {
        //métodos aqui
    });
}
    
10.08.2018 / 01:18
1

Just declare your method as async and put the return type Task , which would be void multithread.

Here is an example:

using System.Threading.Tasks;
using System.Net.Http;

public async Task ExecutarMetodoAsync()
{
    using (var httpClient = new HttpClient())
    {
        // Exemplo
        await httpClient.PostAsync("", null);
    }
}

If you need to return some value you set the return type of Task , example below:

using System.Threading.Tasks;
using System.Net.Http;

public async Task<string> ExecutarMetodoAsync()
{
    using (var httpClient = new HttpClient())
    {
        // Exemplo
        return await httpClient.GetStringAsync("");
    }
}
    
10.08.2018 / 02:07