-1

I have a set of SQL commands that don't return a query, only the amount of affected records. They run in different servers.

They can run simultaneously, I don't need to wait one finish to start another. I'm developing a C# app, I'd like to execute them all in parallel, and then wait for them all to finish and get their int returns.

The first idea is to use multiple threads. I create a thread to run each SqlCommand.ExecuteNonQuery(). Maybe I create a list of bools, that are set to true when the execution finishes. Then, on the main thread, I keep verifying these bools and sleep if any of them is false. A try-finally would set the bool to true even if an Exception is thrown.

Is that the best solution? Can anybody think a better way to do it?

Hikari
  • 3,797
  • 12
  • 47
  • 77
  • [`ExecuteNonQueryAsync()`](https://msdn.microsoft.com/en-us/library/system.data.common.dbcommand.executenonqueryasync(v=vs.110).aspx) + [Task.WaitAll()](http://stackoverflow.com/q/25009437/1997232). – Sinatr Jun 06 '16 at 15:03
  • What problem are you facing with current implementation? – Nikhil Vartak Jun 06 '16 at 15:04
  • @Think2ceCode1ce do you mean the idea I provided? I didn't implement it yet, I'm asking if it's the best or if there is a better one. – Hikari Jun 07 '16 at 12:54

1 Answers1

3

Depending on your .NET Version and your environment, you could use async await for that:

public static async Task ExecuteInParallel(SqlCommand[] commands)
{
    var sqlTasks = commands.Select(c => ExecuteNonQueryAsync());
    await Task.WhenAll(sqlTasks);
}

To block the thread and wait for all commands to finish:

Task.WhenAll(sqlTasks).Wait();

Note however that blocking may lead to a deadlock.

To handle completion asynchronously you can either await the method or use ContinueWith.

Oliver Hanappi
  • 12,046
  • 7
  • 51
  • 68
  • Thanks! gonna try that. Indeed, I'd be more confortable with a function that returns if it's already running and I sleep than a function that waits. But I suppose the queries will return/throw Exception when configured timeouts are reached, right? – Hikari Jun 07 '16 at 12:56