首页 > 代码库 > C#线程总结

C#线程总结

using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading;namespace Guoqingxunliang{    class Program    {        public delegate int TakesAWhileDelegate(int data,int ms);        static int TakesAWhile(int data, int ms)        {            Console.WriteLine("takesawhile started");            Thread.Sleep(ms);            Console.WriteLine("takesawhile completed");            return ++data;        }        static void TakesAWhileCompleted(IAsyncResult iar)        {            if (iar == null) throw new ArgumentNullException("iar");            TakesAWhileDelegate dl = iar.AsyncState as TakesAWhileDelegate;            Trace.Assert(dl!=null,"Invalid object type");            int result=dl.EndInvoke(iar);            Console.WriteLine(result);        }        static void Main(string[] args)        {            #region 异步委托                         TakesAWhileDelegate dl = TakesAWhile;            //验证委托是否完成            IAsyncResult iar = dl.BeginInvoke(1,300,null,null);            while (!iar.IsCompleted)//只要委托没有完成其任务,程序的主线程就继续执行循环            {                Console.WriteLine(".");                Thread.Sleep(50);            }            int result = dl.EndInvoke(iar);            Console.WriteLine("result:{0}",result);            #endregion             #region 句柄等待            TakesAWhileDelegate dl_1 = TakesAWhile;            IAsyncResult ar = dl_1.BeginInvoke(1,3000,null,null);            while (true)            {                Console.WriteLine(".");                if (ar.AsyncWaitHandle.WaitOne(50, false))                {                    Console.WriteLine("can get the result now");                    break;                }            }            int resu = dl_1.EndInvoke(ar);            Console.WriteLine(resu);            #endregion             #region 异步回调            TakesAWhileDelegate dl3 = TakesAWhile;            //使用回调方法,必须注意这个方法从委托线程中调用,而不是从主线程中调用            ///最后一个参数,可以传递任意对象,以便从回调方法中访问它,传递委托实例很有用,            ///这样回调方法就可以使用它获得异步方法的结果            dl3.BeginInvoke(1,3000,TakesAWhileCompleted,dl3);            for (int i = 0; i < 100; i++)            {                Console.WriteLine(".");                Thread.Sleep(30);            }            #endregion             #region 线程            #endregion         }    }}

  参考:C#高级编程

C#线程总结