线程

看到了同学们的博客才发现这节课讲的是18~22章

先介绍一下线程;

ppt上给的例子不知道为什么运行不出来

 class Program
    {
        static void Main(string[] args)
        {
            Thread myThread = new Thread(new ThreadStart(Incrementer));          
            myThread.Start();
        }

        public delegate void ThreadStart();
       
        public void Incrementer()
        {

            for (int i =0;i<1000;i++)
            {
                Console.WriteLine("Incrementer: {0}", i);
            }               
                                                                    
        }
        
    }

然后改成了

class Program
    {
        static void Main(string[] args)
        {
            Thread myThread = new Thread(Incrementer);          
            myThread.Start();
        }

        public delegate void ThreadStart();
       
        static void Incrementer()
        {

            for (int i =0;i<1000;i++)
            {
                Console.WriteLine("Incrementer: {0}", i);
            }               
                                                                    
        }
        
    }

貌似是静态的关系?

接下来如何杀死一个进程

Typically, threads die after running their course.

1.Use a keepalive flag, check the flag periodically.

2.Use Thread.Interrupt() method, ask the thread to kill itself. When thread is blocked in wait, sleep, or join state, ThreadInterruptedException will be thrown, which the thread can catch.

3.Use Thread.Abort() method, this causes ThreadAbortException exception to be thrown, which the thread can catch.

然后不得不说一下前台进程和后台进程

在网上找了一些例子;

默认情况下,线程都是前台线程,意味着任何一个前台线程正在运行,程序就是运行的。而后台线程在所有前台线程终止时也会立即终止。

把线程从前台改为后台,线程在CPU调度器的优先级和状态是不会改变的。

class Program
    {
        static void Main(string[] args)
        {
            Thread worker = new Thread(delegate()
                {
                    Console.ReadLine();
                });
            if (args.Length > 0)
                worker.IsBackground = true;

            worker.Start();
        }
        
    }

  

如果这个程序执行时不带参数,worker线程默认是前台线程,并且会在ReadLine这一行等着用户输入。同时,主线程退出,但是程序会继续运行,因为ReadLine也是前台线程。如果传了一个参数给Main函数,worker线程的状态则被设置成后台状态,程序几乎会在主线程结束时立即退出--终于ReadLine。当后台线程以这种方式终止时,任何代码都不再执行了,这种代码是不推荐的,所以最好在程序退出前等待所有后台线程,可以用超时时间(Thread.Join)来做。如果因为某些原因worker线程一直不结束,也能终止这个线程,这种情况下最好记录一下日志来分析什么情况导致的。

在Windows Form中被抛弃的前台线程是个潜在的危险,因为程序在主线程结束将要退出时,它还在继续运行。在Windows的任务管理器里,它在应用程序Tab里会消失,但在进程Tab里还在。除非用户显式地结束它。

常见的程序退出失败的可能性就是忘记了前台进程。

原文地址:https://www.cnblogs.com/czyhhxx/p/4495783.html