Several threads in c #

1

Hi, I'm making an application where I need to run a call to an Api in the background:

Main{
    Metodo();
} 
Metodo(){
   for(i=0,i<100,i++){Metodo2(i)
}
Método2(int i){    
    apiThread2 = new Thread(() => LlamadaAUnaApi);
    apiThread2.IsBackground = true;
    apiThread2.Start();
}

The thing is that the application ends before the Threads run, I have tried to add them to a Threads list but when the Método2 ends they are not active apiThread2 . I know that if at the end of método2 I do apiThread2.Join(); wait for that thread but I would like as long as Metodo() continue with their things and would like to do the Join at the end of the Main running the list of Threads.

Is this possible in any way?

    
asked by jooooooooota 16.05.2017 в 16:40
source

1 answer

4

For me a good solution is to use async/await . I give you an example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(() => Metodo()).Wait();

            Console.ReadKey();
        }

        public async static Task CallApiAsync(int apiCall)
        {
            Console.WriteLine($"Llamada a API {apiCall}");
        }

        public async static Task Metodo()
        {
            List<Task> jobs = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                Task job = CallApiAsync(i); // se asigna una Task
                jobs.Add(job);
            }

            await Task.WhenAll(jobs); // esperar la ejecución de las llamadas a API
        }

    }
}
    
answered by 17.05.2017 в 09:27