How to wait for multiple tasks to finish to run the next line?

Asked

Viewed 53 times

0

I have a button normal that performs three tasks, I want that when the tasks are running stay on the same line until the work is finished, without locking the program.

I know there is a method of its own Task ContinueWith() and Wait(), but I’m new to the asynchrony part.

        private void Btn_Click(object sender, EventArgs e)
        {
            Tarefas(); // permancer nessa linha enquanto não terminar
            MessageBox.Show("Terminado!");
        }


        private void Tarefas()
        {
            Task.Run(() =>
            {
                //...
            });
            Task.Run(() =>
            {
                //...
            });
            Task.Run(() =>
            {
                //...
            });
        }

How do I work with multiple tasks managing all within a method and finally take this method and know if all within it are finished?

  • Just out of curiosity: why do you need these Task’s?

  • I am developing a random color ARGB using Color.Fromargb(), each color will have a Number. Ex: Color.Fromargb(1,2,3)

  • And you need to use Task’s for that? Why don’t you synchronise?

  • Not to crash the program, I learned just by doing this way using tasks rsrs

  • You say don’t lock the UI?

  • That, my WF app

Show 1 more comment

1 answer

2


Probably no need to use Task there (or any kind of multithreading).

But without getting into this merit, I think you look for the method WaitAll.

using System;
using System.Threading.Tasks;
using static System.Console;

class MainClass {
    public static void Main (string[] args) {        
        Tarefas();    
        WriteLine("FIM");
    }

    static void Tarefas() {
        var t1 = Task.Run(() => 
        {
            for(int i = 0; i < 10; i++) WriteLine(i);
        });

        var t2 = Task.Run(() => 
        {
            for(int i = 10; i < 20; i++) WriteLine(i);
        });

        Task.WaitAll(t1, t2);
    }
}

See working on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.