您的位置:首页 > 其它

多线程操作之异步委托

2012-12-18 10:41 344 查看
多线程操作之异步委托
这里做了一个多线程操作的总结,这里总结了通过异步委托来实现多线程操作。

定义一个委托,是创建一个线程的最简单的方法,并且异步调用它。委托是方法的类型安全的引用。同时委托还智齿异步调用方法。

委托使用线程池来完成异步任务。

当自己的程序使用异步委托的时候,委托会自动创建ige执行线程的任务。委托使用线程池完成异步任务,所有的异步委托调用,都会通过调用系统线程池中的线程来完成调用异步任务。

在下面的简单例子中,我们定义了一个异步委托,并在每次输出的时候显示该函数运行在哪个线程中。

在异步委托中,可以使用三种技术来异步的调用委托。下面分别介绍三种调用异步委托的方法。

1. 投票判断异步委托是否完成

在委托中调用BeginInvoke()方法,返回IAsyncResult结果。程序的源代码如下:

[csharp] 

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.Threading; 

 

namespace AsyncDelegate 



    class Program 

    { 

        public delegate int TakeSomeTimeDelegate(int data,int ms); 

 

        static void Main(string[] args) 

        { 

            TakeSomeTimeDelegate dl=TakeSomeTime; 

            IAsyncResult ar=dl.BeginInvoke(1,200,null,null); 

 

            while (!ar.IsCompleted) 

            { 

                Console.WriteLine("."); 

                Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId); 

                Thread.Sleep(50); 

            } 

 

            int result = dl.EndInvoke(ar); 

            Console.WriteLine("Result:{0}", result); 

        } 

 

        static int TakeSomeTime(int data, int ms) 

        { 

            Console.WriteLine("TakeSomeTime started!"); 

            Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId); 

            Thread.Sleep(ms); 

            Console.WriteLine("TakeSomeTime Completed!"); 

            return ++data; 

        } 

    } 



该程序的输出结果如图:

 


可以看到主线程和异步委托线程是同时执行的。

如果在委托结束之前不等待委托完成其他任务就结束主线程,委托线程就会停止。

int result = dl.EndInvoke(ar); 这里的EndInvoke()函数会一直等在异步委托完成并在异步委托完成之前阻断主线程。这样就可以通过这个函数保证异步委托能够正确完成。

 

2. 等待句柄判断异步委托完成

通过AsyncWatiHandle属性,访问等待句柄。WaitOne()方法阻断当前线程,直到异步调用线程完成返回可以利用的句柄以后再执行当前线程。

程序:

[html]

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.Threading; 

 

namespace AsyncDelegate 



    class Program 

    { 

        public delegate int TakeSomeTimeDelegate(int data,int ms); 

 

        static void Main(string[] args) 

        { 

            TakeSomeTimeDelegate dl=TakeSomeTime; 

            IAsyncResult ar=dl.BeginInvoke(1,200,null,null); 

 

            while (true) 

            { 

                Console.WriteLine("."); 

                Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId); 

                if (ar.AsyncWaitHandle.WaitOne(100, false)) 

                { 

                    Console.WriteLine("Can get the result now"); 

                    break; 

                } 

            } 

 

            //while (!ar.IsCompleted) 

            //{ 

            //    Console.WriteLine("."); 

            //    Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId); 

            //    Thread.Sleep(50); 

            //} 

 

            int result = dl.EndInvoke(ar); 

            Console.WriteLine("Result:{0}", result); 

        } 

 

        static int TakeSomeTime(int data, int ms) 

        { 

            Console.WriteLine("TakeSomeTime started!"); 

            Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId); 

            Thread.Sleep(ms); 

            Console.WriteLine("TakeSomeTime Completed!"); 

            return ++data; 

        } 

    } 



运行结果:

 

 


 

ar.AsyncWaitHandle.WaitOne()阻断了当前线程, 直到异步调用线程完成获得可以利用的句柄以后再次执行当前线程。

 

3. 利用异步回调函数判断异步调用线程是否结束

 

回调函数的操作比较复杂, 而且对于程序的理解和维护造成非常大的困难。所以一般情况下能不用回调函数就不要使用回调函数。

 

使用回调函数,必须注意这个函数从委托线程中调用,而不是从主线程中调用回调函数。

[csharp]

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.Threading; 

 

namespace AsyncDelegate 



    class Program 

    { 

        public delegate int TakeSomeTimeDelegate(int data,int ms); 

 

        static void Main(string[] args) 

        { 

            TakeSomeTimeDelegate dl=TakeSomeTime; 

            IAsyncResult ar = dl.BeginInvoke(1, 200, TakeSomeTimeCompleted, dl); 

            for (int i = 0; i < 10;i++ ) 

            { 

                Console.WriteLine("."); 

                Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId); 

                Thread.Sleep(50); 

            } 

 

            //int result = dl.EndInvoke(ar); 

            //Console.WriteLine("Result:{0}", result); 

        } 

 

        static int TakeSomeTime(int data, int ms) 

        { 

            Console.WriteLine("TakeSomeTime started!"); 

            Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId); 

            Thread.Sleep(ms); 

            Console.WriteLine("TakeSomeTime Completed!"); 

            return ++data; 

        } 

 

        static void TakeSomeTimeCompleted(IAsyncResult ar) 

        { 

            if (ar==null) 

            { 

                throw new ArgumentNullException("ar"); 

            } 

            TakeSomeTimeDelegate dl = ar.AsyncState as TakeSomeTimeDelegate; 

            int result = dl.EndInvoke(ar); 

            Console.WriteLine("result : {0}", result); 

            //Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId); 

        } 

    } 



 

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: