How Create Threads Using Task

65 Views Asked by At

I have a query to a DB which returns the correct data

public async Task<IEnumerable<FacturaDeVentaSP>> ConsultaBD(int page, int row)
{           
    try
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            return await connection.QueryAsync<FacturaDeVentaSP>("facturadeventaSP",
                        parameter, commandType: System.Data.CommandType.StoredProcedure);
        }
    }
    catch (Exception ex)
        {
            throw ex;
        }
    }

What I want is to create x execution threads and within each thread make x requests to the DB.

Task[] tasks = new Task[countThreads];

for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew(()=>new Random().NextDouble());};                
}

How could I execute the ConsultaDB() method x times on each Thread

1

There are 1 best solutions below

2
T.S. On

Instead of Factory, use Task.Run

Task[] tasks = new Task[countThreads];

for (int i = 0; i < tasks.Length; i++)
{
    tasks[i] = Task.Run(() =>  .... };
}

Task.WaitAll(tasks);