c#多线程

来源:互联网 发布:mysql教程pdf 编辑:程序博客网 时间:2024/06/06 00:24

使用ThreadPool的QueueUserWorkItem()方法发起一次异步的线程执行很简单,但是该方法最大的问题是没有一个内建的机制让你知道操作什么时候完成,有没有一个内建的机制在操作完成后获得一个返回值。为此,可以使用System.Threading.Tasks中的Task类。

构造一个Task<TResult>对象,并为泛型TResult参数传递一个操作的返回类型。

using System.Threading;using System;using System.Threading.Tasks;namespace Test{    class Program    {        private static Int32 Sum(Int32 n)        {            Int32 sum = 0;            for (; n > 0; --n)            {                checked { sum += n; }            }            return sum;        }        static void Main()        {            Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 1000);            t.Start();            t.Wait();            Console.WriteLine(t.Result);            Console.ReadKey();                }    }}


由于线程的创建和销毁需要耗费一定的开销,过多的使用线程会造成内存资源的浪费,出于对性能的考虑,于是引入了线程池的概念。线程池维护一个请求队列,线程池的代码从队列提取任务,然后委派给线程池的一个线程执行,线程执行完不会被立即销毁,这样既可以在后台执行任务,又可以减少线程创建和销毁所带来的开销。

线程池线程默认为后台线程(IsBackground)。

using System;using System.Threading;namespace Test{    class Program    {        static void Main()        {            ThreadPool.QueueUserWorkItem(TestMethod, "Hello");        }        public static void TestMethod(object data)        {            string str = data as string;            Console.WriteLine(str);        }    }}



一个任务完成时,自动启动一个新任务。
一个任务完成后,它可以启动另一个任务,下面重写了前面的代码,不阻塞任何线程。

using System;using System.Threading;using System.Threading.Tasks;namespace Test{    class Program    {        static void Main()        {            Task<Int32> t = new Task<Int32>(n=>Sum((Int32)n),1000);            t.Start();            Task cwt=t.ContinueWith(task=>Console.WriteLine("The result is {0}",t.Result))            Console.ReadKey();        }        private static Int32 Sum(Int32 n)        {            Int32 sum = 0;            for(;n>0;--n)            {                checked { sum += n; }            }            return sum;        }    }}



委托的异步调用:BeginInvoke() 和 EndInvoke()

using System;using System.Threading;using System.Threading.Tasks;namespace Test{    public delegate string MyDelegate(object data);    class Program    {        //线程函数        public static string TestMethod(object data)        {            string str = data as string;            return str;        }        //异步回调函数        public static void TestCallback(IAsyncResult data)        {            Console.WriteLine(data.AsyncState);        }        static void Main(string []args)        {            MyDelegate mydelegate = new MyDelegate(TestMethod);            IAsyncResult result = mydelegate.BeginInvoke("Thread Param", TestCallback, "Callback Param");            string resultstr = mydelegate.EndInvoke(result);            Console.ReadKey();        }    }}



原创粉丝点击