Tuesday, 21 August 2018

C#: Background threads

Background threads are low priority threads, these are mainly used for background processing.

How to make a thread as background thread?
Every thread has a property ‘IsBackground’, by setting this property to True, we can make the thread as background thread.

Example
Thread t = new Thread(Print);
t.IsBackground = true;

Program.cs
using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main()
        {
            Thread t = new Thread(Print);
            t.Name = "Printer Thread";
            t.IsBackground = true;
            t.Start();
            t.Join();
        }

        static void Print()
        {
            Thread.Sleep(2000);
            Console.WriteLine("{0} Executing the print process", Thread.CurrentThread.Name);
        }
    }
}

Output
Printer Thread Executing the print process


As you observe, I used 't.join()' statement after starting the thread. It is because once all foreground threads finish their execution, the application ends, and application terminates all the background threads. To confirm this, comment 't.Join()' statement and re-run Program.cs file.


Previous                                                 Next                                                 Home

No comments:

Post a Comment