C# Thread()

Leave a comment

C# applications are often required to implement multithreaded functionality. Thanks to the .NET Framework, implementing threading is not difficult.

In C# there are different ways we can create threads. Here we will look at using Thread.

The Thread class is part of System.Threading. It is useful in that you can control many aspects of threads, such as whether to run in the foreground or background, the thread pool etc.

We will go through an example of creating a thread. Create a new console app in Visual Studio:

Note we are using:

using System.Threading.Tasks;

We will also add:

using System.Threading;

And the code:

 static void Main(string[] args)
 {
 Thread t = new Thread(() =>
 {
 Console.WriteLine("Thread is running");
 });
 t.Start();
 }
 }

Note the notation, we can also write this as:

            new Thread(() =>
            {
                Console.WriteLine("Thread is running");
            }).Start();

When we run this, we can see there are several attributes to our thread:

We can see in the debug window, the thread has a Main Thread, and a Worker Thread. The thread has defaulted to run in the foreground. Foreground threads run even if the application itself has exited. Background threads will exit with the application:

We can switch this to a background thread by setting the property:

 Thread t = new Thread(() =>
 {
 Console.WriteLine("Thread is running");
 });
 t.IsBackground = true;
 t.Start();

Running this, we can see one main thread:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *