HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Running 2 sets of tasks at the same time

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethetimetasksrunningsets

Problem

Currently, my team and I have 2 types of databases that are updated periodically, SQL Server and Access. Also, we run specialized reports based on those databases.

Basically, we have 4 tasks that need to be completed:

  • Update SQL Server



  • Publish SQL Server Reports



  • Update Access Databases



  • Publish Access Db reports



Access takes forever to run, so I am trying to make my code run the task of Updating Access and Publishing Access reports at the same time that I am updating SQL Server and publishing those reports.

Can someone verify if I am on the right path, or maybe share a link that better explains async?

static void Main(string[] args)
{
    var cs1 = new _1_UpdateSQL();
    var cs2 = new _2_PublishSQLRpts();

    Task t = TriggerAccess();

    cs1.UpdateSqlCodeOnly();
    cs2.PublishSqlRptsCodeOnly();
    t.Wait();
}

static async Task TriggerAccess()
{
    var cs3 = new _3_UpdateAccessDb();
    var cs4 = new _4_PublishAccessRpts();

    await Task.Run(() => cs3.UpdateAccessDbCodeOnly());
    await Task.Run(() => cs4.PublishAccessRptsCodeOnly());

}

Solution

When I have to manage multiple threads, I make sure all processing is complete, typically by using WaitAll.

List tasks = new List();
tasks.Add(Task.Run(() => { TriggerAccess(); }));
tasks.Add(Task.Run(() => { TriggerSQL(); }));
Task.WaitAll(tasks.ToArray());


This also allows me to use methods in a non-threaded capacity for testing and to easily add additional threads when the need arises. I can then also return actual data from a method, if I need to, instead of just a thread.

The difference between running the method in a thread and having the method be an async thread is that an async method waits until the first await statement to return to the main thread for processing whereas threading the method immediately continues to the next statement in the main method.

Link and http://msdn.microsoft.com/en-us/library/hh156513.aspx are very helpful for me.

Code Snippets

List<Task> tasks = new List<Task>();
tasks.Add(Task.Run(() => { TriggerAccess(); }));
tasks.Add(Task.Run(() => { TriggerSQL(); }));
Task.WaitAll(tasks.ToArray());

Context

StackExchange Code Review Q#59147, answer score: 10

Revisions (0)

No revisions yet.