C # Thread3-- foreground thread a background thread

By default, the display thread is created foreground thread, the process waits inside all foreground threads executing the exit will end

1. Create a default thread is the foreground thread

2. The process will wait for all the threads executing the reception ended, if there is a background thread will be interrupted and forced to withdraw.

3. If you close the program, but there are no foreground thread end, the program will not be completely closed, the Task Manager can still see the process.

3. to set the thread by setting Thread.IsBackground property is a foreground or background.

Example 1 (two foreground thread)

 

class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(Task1);
            Thread thread2 = new Thread(Task2);
            thread1.Start();
            thread2.Start();
        }
        private static void Task1()
        {
            Thread.Sleep(1000);
            Console.WriteLine("hello i am first");
        }
        private static void Task2()
        {
            Thread.Sleep(5000);
            Console.WriteLine("hello i am first");
        }
    }

 

The console will wait two threads executing the exit

Example 1 (Thread1 foreground, Thread2 background)

class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(Task1);
            Thread thread2 = new Thread(Task2);
            thread1.Start();
            thread2.IsBackground = true;//设置2为后台线程
            thread2.Start();
        }
        private static void Task1()
        {
            Thread.Sleep(1000);
            Console.WriteLine("hello i am first");
        }
        private static void Task2()
        {
            Thread.Sleep(5000);
            Console.WriteLine("hello i am first");
        }
    }

The console will automatically exit after running Thread1, but this time Thread2 not yet executed, because he is being forced to interrupt a background thread so

Finally: If the program does not define a complete foreground thread, the main program does not end normally, so before colleagues encountered a WPF program closed, but still occupy memory, quickly navigate to a foreground thread is not performed complete.

 

 

Guess you like

Origin www.cnblogs.com/qwqwQAQ/p/11939404.html