Wait till the background thread completed

Earlier we see that the application dont wait till the background thread is completed. Let's run the below example and see the output.



namespace My_Samples
{
using System;
using System.Threading;

public class MyClass
{
public void MyMethod()
{
for (int i = 0; i < 10; i++)
{
System.IO.File.AppendAllText("c:\\thread.txt", i.ToString() + Environment.NewLine);
Thread.Sleep(100);
}
}
}

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
ThreadStart entryPoint = new ThreadStart(obj.MyMethod);
Thread thread = new Thread(entryPoint);
thread.IsBackground = true;
thread.Start();
for (int i = 0; i < 10; i++)
{
System.IO.File.AppendAllText("c:\\Main.txt", i.ToString() + Environment.NewLine);
Thread.Sleep(10);
}
}
}
}


Main.txt
0
1
2
3
4
5
6
7
8
9

thread.txt
0
1

So the application is completely terminated and all the background threads too. But, I do not want this to be happened and want to wait till all the background thread completes the task. See the below example. I just added the thread.Join() statement which made the magic now. Now the application will wait till the background thread is completed.



namespace My_Samples
{
using System;
using System.Threading;

public class MyClass
{
public void MyMethod()
{
for (int i = 0; i < 10; i++)
{
System.IO.File.AppendAllText("c:\\thread.txt", i.ToString() + Environment.NewLine);
Thread.Sleep(100);
}
}
}
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
ThreadStart entryPoint = new ThreadStart(obj.MyMethod);
Thread thread = new Thread(entryPoint);
thread.IsBackground = true;
thread.Start();

thread.Join();
for (int i = 0; i < 10; i++)
{
System.IO.File.AppendAllText("c:\\Main.txt", i.ToString() + Environment.NewLine);
Thread.Sleep(10);
}
}
}
}

No comments:

Post a Comment