C#线程(一)

来源:互联网 发布:物联网农业数据平台 编辑:程序博客网 时间:2024/06/05 16:17

一、利用Thread的方式
代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;namespace ThreadPool{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("主线程开始");            Thread thread = new Thread(new ThreadStart(ThreadInvoke));            //启动线程            thread.Start();            //主线程持续2000秒钟            Thread.Sleep(2000);            Console.WriteLine("主线程结束");        }        static void ThreadInvoke()        {            for (int i = 0; i < 5; i++)            {                Console.WriteLine("子线程执行第{0}次", i);                //每隔1000毫秒,循环一次                Thread.Sleep(1000);            }        }    }}

执行结果:
主线程开始
子线程执行第0次
子线程执行第1次
主线程结束
子线程执行第2次
子线程执行第3次
子线程执行第4次

主线程和子线程并行执行。

二、利用线程池的方式

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ThreadPoolDemo{    class Program    {        static void Main(string[] args)        {            ThreadPool.QueueUserWorkItem(new WaitCallback(PoolMethod),"hello");            Console.WriteLine("主线程开始");            Thread.Sleep(1000);            Console.WriteLine("主线程结束");        }        static void PoolMethod(Object stateInfo)        {            Console.WriteLine("执行方法 " + stateInfo.ToString());        }    }}

运行结果:
主线程开始
执行方法 hello
主线程结束

0 0
原创粉丝点击