RayK
RayK

Reputation: 51

Asynchronous programming in .Net Console application

I have an application to unzip a folder and merge files, i want to use asynchronous here, i want a thread to unzip a folder and another thread to merge the files in unzipped folder, once the unzip thread complete its task, the app should wait for merger thread to complete. Merger thread(child) is dependent on unzip thread(parent) below is the code i am using inside program.cs file

var t1= Task.Factory.StartNew(() =>
    {                       
       obj.UnZipFiles(files, formats);
    });

inside unzip.cs file

var t2= Task.Factory.StartNew(() =>
    {
        obj.MergeFiles();
    });

In the program.cs file, I have

Task.WaitAll(t1); 

My application is not waiting for child thread to complete, Any help would be appreciated.

Upvotes: 1

Views: 204

Answers (1)

Alex
Alex

Reputation: 987

When creating the second task, use Continuation.

E.g.

var t1 = new Task(() => obj.UnZipFiles(files, formats));
var t2 = t1.ContinueWith((t) => obj.MergeFiles());
t1.Start();

This will ensure the second task only gets triggered when the first task is completed.

Upvotes: 2

Related Questions