-1

I am facing some problem when try to run multiple methods simultaneously with some sort of priority. Below is my code:

public static void Main(string[]args)
{
  List<string> keyList = new List<string>();
  var connecttask = Task.Factory.StartNew(() => getkeyword(0)).ContinueWith(prevTask => connect(1000, keyList));
}

The getkeyword() method must run first because it has to pass a List parameters to connect() method in order to let connect() method to perform its task.

However, this code will not run unless I insert some Console.WriteLine under the code, for example:

public static void Main(string[]args)
{
  List<string> keyList = new List<string>();
  var connecttask = Task.Factory.StartNew(() => getkeyword(0)).ContinueWith(prevTask => connect(1000, keyList));
  Console.WriteLine("Connecting...");
  Console.ReadLine();
}

Why does this happen? I do not want the Console.WriteLine or even Console.ReadLine take in place here because this is the code that I'm going to implement behind a UI button. Is there any way to solve this or any other method to run multiple method simultaneously but with a priority?

Thanks.

Sivvie Lim
  • 784
  • 2
  • 14
  • 43
  • It sounds like your program is exiting, which would be the expected behavior with the code in your first snippet. It's the Console.ReadLine that's preventing it from exiting and allowing the tasks to 'run'. You need to Wait on the result of your task otherwise – pinkfloydx33 Oct 29 '17 at 15:50
  • Ah I add the wait method in there and it works! Thank you so much!! @pinkfloydx33 – Sivvie Lim Oct 29 '17 at 15:52

1 Answers1

0

Apparently I just did not wait for the task to be completed. Here's the code snippet to prevent it exited:

public static void Main(string[]args)
{
    List<string> keyList = new List<string>();
    var connecttask = Task.Factory.StartNew(() => getkeyword(0)).ContinueWith(prevTask => connect(1000, keyList));
    connecttask.Wait();
}
Sivvie Lim
  • 784
  • 2
  • 14
  • 43