Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main Thread terminates before Task thread completion

Hi i need your help guys,

i declared new Task inside my main method like this:

   static void Main(string[] args)
   {    
       Task firstTask = Task.Factory.StartNew(()getPackage(packageId));
       Task secondTask=firstTask.ContinueWith((_=>UpdatePackage(myPackage)));       
   }

My problem is, the main thread terminates before my task completes its action. How should I wait Task to complete its action before terminating the main thread?

like image 735
MasterBettor Avatar asked Oct 20 '25 08:10

MasterBettor


2 Answers

Add the following code to make your main thread block until you hit enter in the command window.

Console.Readline();

UPDATE:

If you want a non-interactive solution, then you could just wait for all the tasks to complete.

Task.WaitAll(firstTask, secondTask);
like image 76
Mike Hixson Avatar answered Oct 22 '25 23:10

Mike Hixson


You can use an alternate paradigm for dealing with this.

static void Main(string[] args)
{
    MainAsync().Wait();
}
static async Task MainAsync()
{
    Task firstTask = new Task(()=>getPackage(packageId));
    firstTask.ContinueWith(()=>UpdatePackage(myPackage)));
    await firstTask.Run();
}

Be careful with mixing asynchronous and synchronous code like this, but, for your purposes, this should work fine (if this were winforms or WPF, you might have to worry about messaging to the UI thread, but that's not relevant here.

like image 45
willaien Avatar answered Oct 22 '25 23:10

willaien