Reputation: 9387
I am learning TPL C# when i call an infinite while loop inside a task it terminates with out any error. am i doing something wrong? below is the sample code.
class Work2
{
public void DoWork()
{
List<string> scenarios = new List<string>();
scenarios.Add("work");
scenarios.Add("climb");
scenarios.Add("walk");
scenarios.Add("run");
List<int> id = new List<int>();
id.Add(1);
id.Add(2);
id.Add(3);
id.Add(4);
for (int i = 0; i < 2; i++)
{
Task.Factory.StartNew(() =>
{
workInstance(id[i], scenarios);
}, TaskCreationOptions.LongRunning);
Thread.Sleep(500);
}
}
public void workInstance(int id, List<string> scenario)
{
string Guid = System.Guid.NewGuid().ToString();
for (int i = 0; i < scenario.Count(); i++)
{
scenario[i] = scenario[i] + " " + Guid + " " + Thread.CurrentThread.ManagedThreadId;
}
while (true)
{
for (int i = 0; i < scenario.Count(); i++)
{
Console.WriteLine(scenario[i]);
}
}
}
}
Upvotes: 1
Views: 2127
Reputation: 244757
The problem is that you're not waiting for the Task
s to complete. A Process
ends when all its foreground Thread
s complete. If you create a Thread
manually, by default it's created as a foreground thread, so your application won't end until all the Thread
s you created do.
But Task
s are (by default) running on background threads (even if you specify LongRunning
). This means you application will end even if there are some Task
s still running.
What you should do to fix that is to wait for all the Task
s to finish. Something like:
var tasks = new Task[2];
for (int i = 0; i < 2; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
workInstance(id[i], scenarios);
}, TaskCreationOptions.LongRunning);
}
Task.WaitAll(tasks);
Upvotes: 2
Reputation: 3573
It is a infinite loop as you thought, check the following code
static void Main(string[] args)
{
Work2 w = new Work2();
w.DoWork();
Console.ReadKey();
}
Note that I have added, the following code Console.ReadKey();
I now see a scrolling window with the output being printed and its still running on my PC :)
Debug your code and you will see that the threads being called in the workInstance method have
Thread.CurrentThread.IsBackground=true
When the main thread exits, i.e. your application exits, the .NET Framework will automatically kill any threads whose IsBackground property is set to "True"
For you reference,
"A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process."
Upvotes: 1