C#中的前台线程和后台线程的区别
生活随笔
收集整理的這篇文章主要介紹了
C#中的前台线程和后台线程的区别
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
-
前臺線程:應(yīng)用程序必須運行完所有的前臺線程才能退出,默認(rèn)創(chuàng)建的線程都是前臺線程。
-
后臺線程:應(yīng)用程序可以不必考慮后臺線程是否已經(jīng)運行完畢(包括正常退出和異常退出),只要所有的前臺線程結(jié)束,后臺線程自動結(jié)束。
一般后臺線程用于處理時間較短的任務(wù),如在一個Web服務(wù)器中可以利用后臺線程來處理客戶端發(fā)過來的請求信息。而前臺線程一般用于處理需要長時間等待的任務(wù),如在Web服務(wù)器中的監(jiān)聽客戶端請求的程序,或是定時對某些系統(tǒng)資源進(jìn)行掃描的程序。
如何將線程設(shè)置為前臺或后臺線程?
thread1.IsBackground = false;//將thread1設(shè)置為前臺線程(默認(rèn)狀態(tài))
fThread.IsBackground = true;//將thread1設(shè)置為后臺線程
修改如下代碼中的bThread線程的前后臺屬性可體會前臺線程和后臺線程的區(qū)別:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading;namespace ConsoleApplication1 {class Program{static void Main(string[] args){ThreadTest backGround = new ThreadTest(3);Thread fThread = new Thread(new ThreadStart(backGround.Test));fThread.Name = "前臺線程";fThread.IsBackground = false;ThreadTest backGround1 = new ThreadTest(5);Thread bThread = new Thread(new ThreadStart(backGround1.Test));bThread.IsBackground = true;bThread.Name = "后臺線程";fThread.Start();bThread.Start();}}class ThreadTest{private int count = 0; //私有數(shù)據(jù)//構(gòu)造函數(shù)public ThreadTest(int count){this.count = count;}public void Test(){string threadName = Thread.CurrentThread.Name;for (int i = 0; i < count; i++){Console.WriteLine("{0}計數(shù):{1}", threadName, i);Thread.Sleep(500);}Console.WriteLine("{0}完成計數(shù)", threadName);}} }當(dāng)bThread.IsBackground = true時,運行結(jié)果如下:前臺線程運行完成后后臺線程立即結(jié)束。
當(dāng)bThread.IsBackground = false時,運行結(jié)果如下:所有前臺線程運行結(jié)束程序才結(jié)束。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的C#中的前台线程和后台线程的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高响应比优先调度算法(HRRN)例题详解
- 下一篇: C#控件跨线程内容更新