首页 > 编程语言 > 详细

C#线程总结

时间:2014-10-04 09:38:16      阅读:276      评论:0      收藏:0      [点我收藏+]
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#线程总结

原文:http://www.cnblogs.com/kuugachen/p/4005627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!