多线程操作之异步委托

在应届生找工作的时候,多线程操作几乎是所有的公司都会问及的一个基本问题。

这里做了一个多线程操作的总结,这里总结了通过异步委托来实现多线程操作。

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

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

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

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

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

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

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

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()方法阻断当前线程,直到异步调用线程完成返回可以利用的句柄以后再执行当前线程。

程序:

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. 利用异步回调函数判断异步调用线程是否结束

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

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

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);
        }
    }
}


运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值