0

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

T.S.
  • 14,772
  • 10
  • 47
  • 66
  • 1
    If you're querying a DB then that's IO and you don't need separate threads. Just use `async` and `await` to get Tasks that you can await. That way you can issue new queries while waiting for the IO from the others to finish. – juharr Jun 08 '20 at 20:29
  • [This](https://stackoverflow.com/a/44149141/2501279) EF related, but i think it will be around the same with dapper/or ormless handling in general. So you will need to consider if actually more cumbersome code gives you gains in your specific usecase. – Guru Stron Jun 08 '20 at 20:40

1 Answers1

-1

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);
T.S.
  • 14,772
  • 10
  • 47
  • 66
  • 1
    That should be enough to get OP running with strange idea they have... For everyone else - use async methods to read from DB - https://stackoverflow.com/questions/39967208/c-sharp-mysql-driver-async-operations. – Alexei Levenkov Jun 08 '20 at 20:30
  • @AlexeiLevenkov I don't disagree that OP has a different logistics issue. However, this is the piece OP had trouble with in their mind – T.S. Jun 08 '20 at 20:32