I run 3 tasks that each perform their role. I thought that adding an async Run program would wait until all tasks were completed, but it was wrong. The loop immediately goes to the string int x=2; . How to wait for tasks?

 public async Task Run() { Task.Factory.StartNew(() => { // Задача 1 } Task.Factory.StartNew(() => { // Задача 2 } Task.Factory.StartNew(() => { // Задача 3 } } private async void button1_Click(object sender, EventArgs e) { await Run(); // он не ожидает завершения задача, а сразу переходит вниз int x = 2; } 

    1 answer 1

    Use await .

     await Task.Factory.StartNew(() => { // Задача 1 }); 

    etc.

    Or if you want to run tasks in parallel, then:

     var t1 = Task.Factory.StartNew(() => { // Задача 1 }); var t2 = Task.Factory.StartNew(() => { // Задача 1 }); var t3 = Task.Factory.StartNew(() => { // Задача 1 }); await Task.WhenAll(t1, t2, t3); 
    • tasks do post-get requests, however, active connection 3 == number of cores. how to increase the number? - Radzhab
    • @Radzhab: I think that equality to the number of cores is a coincidence. Try Task.Run instead of Task.Factory.StartNew , by the way. - VladD