C# 前臺線程與後臺線程區別

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //前臺線程和後臺線程惟一區別就是:應用程序必須運行完全部的前臺線程才能夠退出;
            //而對於後臺線程,應用程序則能夠不考慮其是否已經運行完畢而直接退出,
            //全部的後臺線程在應用程序退出時都會自動結束。
            MessageBox.Show("點擊按鈕啓動了一個前臺線程。\r\n前臺線程:「既然我上臺了,我必定要表演完,否則我跟你沒完!」");
            //前臺線程
            Thread t1 = new Thread(Say);
            t1.IsBackground = false;
            t1.Name = "前臺線程";
            t1.Start();            
        }
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("點擊按鈕啓動了一個後臺線程。\r\n後臺線程:「既然我沒上臺,我受制於應用程序,它關了我就自動關了(舞臺都關了,我在後臺再幹活就沒意思了)!」");
            //後臺線程
            Thread t2 = new Thread(Say);
            t2.IsBackground = true;
            t2.Name = "後臺線程";
            t2.Start();
        }
        private void Say()
        {
            for (int i = 0; i < 100; i++)
            {
                MessageBox.Show("我演,我賣力的演!\n\r把主窗口關了,你看我還在不在?"+i.ToString());
            }
        }
    }
}

建議先啓動一個後臺線程按鈕,感受沒啥吧?而後再啓動一個前臺線程。看看是不是前臺線程很頑強的跟你沒完!絕對讓你看一遍永不忘記!spa

相關文章
相關標籤/搜索