C# 前台线程 后台线程区别

前台线程 会随进程一起结束 不管是否完成,后台线程需要执行完毕,进程才能结束

例子:
class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(Run);
            //t.IsBackground = true;    //前台线程 会随进程一起结束 不管是否完成,后台线程需要执行完毕,进程才能结束
            t.Start();;
        }

        public static void Run()
        {
            FileStream fs = null;
            try
            {
                fs = File.Create("test.txt");
                for(int i = 0;i < 10;++i)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(i.ToString() + "
");
                    fs.Position = fs.Length;
                    fs.Write(bytes, 0, bytes.Length);
                    Thread.Sleep(1000);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }
原文地址:https://www.cnblogs.com/darkif/p/14210558.html