c# 线程化 Thread

来源:互联网 发布:外卖消费人群数据分析 编辑:程序博客网 时间:2024/05/22 06:41
    /// <summary>    /// 线程:独立完成任务。    /// 多线程是编程中最有效用的一种概念。可将一个单任务分解成多个独立执行的线程。    /// </summary>    class Program    {        /// <summary>/// </summary>        /// <param name="args"></param>        static void Main(string[] args)        {            Thread t=new Thread(new ThreadStart(DoSth));            t.Start();            while(true){                Console.WriteLine("I am main...");            }            Console.Read();        }        static void DoSth()        {                          Console.WriteLine("doing....");                        }    }  

 

 


 

        /// <summary>        /// Cancel the thread:        /// Thread.Abort();        /// We don't encourage the person to use .Abort() 去cancel the Thread,we can use the valiable:_stopThread to cancle it(noice:volatile)        /// volatile: tip the compiler that _stopThread can be used by almost threads.该变量不可以由编译器进行优化。并始终具有最新的值        /// </summary>        private static volatile bool _stopThread = false;        static void Main(string[] args)        {            Thread t=new Thread(new ThreadStart(DoSth));            t.Start();            while (!t.IsAlive); //judge the thread is alive or not             Thread.Sleep(1000);            _stopThread = true;            Console.Read();        }        static void DoSth()        {            try            {                while (!_stopThread)                {                    Console.WriteLine("doing....");                }            }            catch (ThreadAbortException ex)            {                Console.WriteLine(ex.Message);            }            finally            {                //clean up the resources,有必要吗?请大神指教!            }        }

 

 

/// <summary>        /// Join(): connect two threads        /// 它的作用就是:在一个线程里,把另一个线程加进来,直到加进来的这个线程挂掉。        /// </summary>        private static volatile bool _stopThread = false;        static void Main(string[] args)        {            Thread t=new Thread(new ThreadStart(DoSth));            t.Start();            while (!t.IsAlive); //judge the thread is alive or not             Thread.Sleep(1000);            _stopThread = true;            t.Join();            Console.WriteLine("Thread ended!");            Console.Read();        }        static void DoSth()        {            try            {                while (!_stopThread)                {                    Console.WriteLine("doing....");                }            }            catch (ThreadAbortException ex)            {                Console.WriteLine(ex.Message);            }            finally            {                //clean up the resources,有必要吗?请大神指教!            }        }    }


 

/// <summary>        /// 向线程传递形参,通常有两种方法:        /// 1,Use the class pack the function.and use the features to transmit the parameter        /// 2,Use the 'ParameterizedThreadStart' delegate        /// There is the first methode above:        /// </summary>        static void Main(string[] args)        {            SomeClass sc=new SomeClass();            sc.msg = " aji";            Thread t=new Thread(new ThreadStart(sc.DoSth));            t.Start();        }        class SomeClass        {            public string msg { get; set; }            public void DoSth()            {                try                {                    while (true)                    {                        Console.WriteLine("doing something..{0}",msg);                    }                }                catch (Exception e)                {                    Console.WriteLine(e.Message);                }            }        }    }

 

 

 /// <summary>        /// 向线程传递形参,通常有两种方法:        /// 1,Use the class pack the function.and use the features to transmit the parameter        /// 2,Use the 'ParameterizedThreadStart' delegate        /// There is the second methode above:        /// </summary>        static void Main(string[] args)        {            Thread t=new Thread(new ParameterizedThreadStart(DoSth));            t.Start(" aji");        }        static void DoSth(object msg)        {            while (true)            {                Console.WriteLine("Doing sth..{0}",msg);            }        }

 

/// <summary>        /// 使用多线程化可以获得同时运行的多个执行线程。当它们同时运行时,会竞争同一组相同的资源,所以必须通过一种机制来确保线程之间的同步和通信        /// 这就是线程的安全性,我们将使用下面的方法去同步线程:        /// Interlocked 类        /// c# lock        /// Monitor 类        /// 好吧,Interlocked 类我不会,下面说说 lock:        /// 其中,obj是为lock作准备,是用于锁定操作的对象实例        /// </summary>        static object obj=new object();        private static int balance = 500;        static void Main(string[] args)        {            Thread t1=new Thread(new ThreadStart(Debit));            t1.Start();            Thread t2=new Thread(new ThreadStart(Credit));            t2.Start();        }        static void Debit()        {                         for (int i = 0; i < 10; i++)                {                    lock (obj)                    {                        balance -= 100;                        Console.WriteLine("debit...balance is {0}", balance);                     }                }         }        static void Credit()        {                           for (int i = 0; i < 15; i++)                {                    lock (obj)                    {                        balance += 100;                        Console.WriteLine("credit...balance is {0}", balance);                     }                }         }

 

/// <summary>        /// 使用多线程化可以获得同时运行的多个执行线程。当它们同时运行时,会竞争同一组相同的资源,所以必须通过一种机制来确保线程之间的同步和通信        /// 这就是线程的安全性,我们将使用下面的方法去同步线程:        /// Interlocked 类        /// c# lock        /// Monitor 类        /// 用 lock不好,不能在执行关键段的中途释放锁,使其他线程来享受资源,执行操作!        /// 现在我们用 Monitor。        /// 其中,Monitor.Enter() 跟 Monitor.Exit() 是配套使用的。.Wait() 和 . Pulse() 功能自己研发        /// </summary>        static object obj=new object();        private static int balance = 500;        static void Main(string[] args)        {            Thread t1=new Thread(new ThreadStart(Debit));            t1.Start();            Thread t2=new Thread(new ThreadStart(Credit));            t2.Start();                    }        static void Debit()        {                     for (int i = 0; i < 10; i++)            {                Monitor.Enter(obj);                    balance -= 100;                    Console.WriteLine("debit...balance is {0}", balance);                    //当收益等于 0,此时不能再减下去了。只能等待                    if (balance == 0) Monitor.Wait(obj);                Monitor.Exit(obj);            }         }        static void Credit()        {            for (int i = 0; i < 15; i++)            {                Monitor.Enter(obj);                    balance += 100;                    //收益不为0,向等待的线程发出唤醒的信号                    if(balance>0) Monitor.Pulse(obj);                    Console.WriteLine("credit...balance is {0}", balance);                 Monitor.Exit(obj);            }         }

 

        /// <summary>        /// 现在在这里贴出一个由线程,委托,等组成的一个Windows Forms的线程实例,就一个电子表:        /// 其实在 WinForm 写线程的好处就是:可以在多线程的情况下更新 UI !,比如多个线程去执行 IO,文件处理,计算等,        /// 然后在 UI 里更新结果。但是 UI 中的控件在一个特定的线程里,调用它会出现安全性的问题,固可以结合下面的成员        /// 来完成的 UI 控件的更新:        /// InvokeRequired() bool型。如果控件是在创建它的线程上被调用,则为false,如果是其他线程,或还没有为该控件创建窗口句柄,则为true        /// Invoke()在拥有控件的底层窗口句柄的线程上执行委托        /// BeginInvoke() 异步调用        /// EndInvoke() 获取BeginInvoke方法启动的异步操作的返回值        ///         /// 其实这些东西都很解释得很官方,这里慢慢懂,下面是实例,里面用到了委托,但不知道是出于什么缘故,        /// 看官们看懂了请不吝赐教,谢谢。        /// </summary>        /// <param name="ctrl"></param>        /// <param name="str"></param>        private delegate void delUpdateControl(Control ctrl, string str);        private delUpdateControl myDelegate;        private void updateLable(Control ctrl, string str)        {            ctrl.Text = str;        }        private void TimeForm_Load(object sender, EventArgs e)        {            myDelegate = new delUpdateControl(updateLable);            Thread t = new Thread(PrintTime);            t.Start();        }        public TimeForm()        {            InitializeComponent();        }        private void PrintTime()        {            try            {                while (true)                {                    if (TimeL.InvokeRequired)                    {                        TimeL.Invoke(myDelegate, new object[]                            {                                TimeL,DateTime.Now.ToString()                            });                        Thread.Sleep(1000);                    }                    else                    {                        TimeL.Text = DateTime.Now.ToString();                    }                }            }            catch (Exception)            {                                throw;            }        }    }

 

    /// <summary>    /// 还有一点要说的就是:C#提供一个叫:BackgroundWorker 控件的东西。它是可以方便提供多线程的方案。    /// 它可以执行运行时间较长的后台任务:网络访问,文件访问等。该控件运行在单独的线程上。    /// 不过代码太长,而且本人才疏学浅,只能将书中的代码抄出来,却也赖得去细细地看,    /// 各位看官看懂了,不吝赐教!    /// </summary>

 

View Code

 

0 0
原创粉丝点击