天天看點

C#多線程——前台線程和背景線程

由于時間片的原因,雖然所有線程在微觀上是串行執行的,但在宏觀上可以認為是并行執行。

線程有兩種類型:前台和背景。我們可以通過線程屬性IsBackground=false來指定線程的前背景屬性(預設是前台線程)。

差別是:前台線程的程式,必須等所有的前台線程運作完畢後才能退出;而背景線程的程式,隻要前台的線程都終止了,那麼背景的線程就會自動結束并推出程式。

用法方向:一般前台線程用于需要長時間等待的任務,比如監聽用戶端的請求;背景線程一般用于處理時間較短的任務,比如處理用戶端發過來的請求資訊。

【前台線程】

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread aThread = new Thread(threadFunction);
            Console.WriteLine("Thread is starting...");
            aThread.Start();
            Console.WriteLine("Application is terminating...");
        }

        public static void threadFunction()
        {
            Console.WriteLine("Thread is sleeping...");
            Thread.Sleep(5000);
            Console.WriteLine("Thread is aborted!");
        }
    }
}
           

【背景線程】 

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread aThread = new Thread(threadFunction);
            aThread.IsBackground = true;
            Console.WriteLine("Thread is starting...");
            aThread.Start();
            Console.WriteLine("Application is terminating...");
        }

        public static void threadFunction()
        {
            Console.WriteLine("Thread is sleeping...");
            Thread.Sleep(5000);
            Console.WriteLine("Thread is aborted!");
        }
    }
}