C#__custom class transfer data and foreground thread and background thread

// Foreground threads and background threads
// By default, threads created with the Thread class are foreground threads. Threads in the thread pool are always background threads.
// When creating a thread with the Thread class, you can set the IsBackground property to indicate a background thread.
// The foreground thread is still executed after the main function is finished, and the background thread is no longer executed after the main function is executed

// DownloadTool class

    class DownloadTool
    {
        public string URL { get; private set; }
        public string Message { get; private set; }

        public DownloadTool(string uRL, string message)
        {
            URL = uRL;
            Message = message;
        }
        public void Download()
        {
            Console.WriteLine("从" + URL + "中下载");
        }
    }

 // main program

    class Program
    {
        static void Main(string[] args)
        {
            DownloadTool download = new DownloadTool("http://www……", "manager");
            Thread t = new Thread(download.Download); 
            t.Start(); // 从http://www……中下载

            // 前台线程和后台线程
            // 默认情况下,用Thread类创建的线程是前台线程。线程池中的线程总是后台线程。
            // 用Thread类创建线程的时候,可以设置IsBackground属性,表示一个后台线程。
            // 前台线程在主函数运行结束后依旧执行,后台线程在主函数执行完毕后不再执行
            var t1 = new Thread(ThreadMain) { IsBackground = true };
            t1.Start();
            Console.WriteLine("Main thread ending now.");

            //Main thread ending now.
            //Thread + stared // 线程同步有一定的时间运行
        }
        static void ThreadMain()
        {
            Console.WriteLine("Thread +" + Thread.CurrentThread.Name + "stared");
            Thread.Sleep(2000);
            Console.WriteLine("Thread +" + Thread.CurrentThread.Name + "end");
        }
    }

Guess you like

Origin blog.csdn.net/qq_57233919/article/details/132476511