C# Thread、ThreadPool、Task、Invoke、BeginInvoke、async、await 汇总

本文将主要经过“同步调用”、“异步调用”、“异步回调”三个示例来说解在用委托执行同一个“加法类”的时候的的区别和利弊。html

首先,经过代码定义一个委托和下面三个示例将要调用的方法:编程

public delegate int AddHandler(int a,int b);
    public class 加法类
    {
        public static int Add(int a, int b)
        {
            Console.WriteLine("开始计算:" + a + "+" + b);
            Thread.Sleep(3000); //模拟该方法运行三秒
            Console.WriteLine("计算完成!");
            return a + b;
        }
    }

同步调用

委托的Invoke方法用来进行同步调用。同步调用也能够叫阻塞调用,它将阻塞当前线程,而后执行调用,调用完毕后再继续向下进行。多线程

public class 同步调用
{
        static void Main()
        {
            Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法类.Add);
            int result = handler.Invoke(1, 2);

            Console.WriteLine("继续作别的事情。。。");

            Console.WriteLine(result);
            Console.ReadKey();
        }
}

同步调用会阻塞线程,若是是要调用一项繁重的工做(如大量IO操做),可能会让程序停顿很长时间,形成糟糕的用户体验,这时候异步调用就颇有必要了。异步

异步调用

异步调用不阻塞线程,而是把调用塞到线程池中,程序主线程或UI线程能够继续执行。 委托的异步调用经过BeginInvoke和EndInvoke来实现。async

public class 异步调用
{
        static void Main()
        {
            Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法类.Add);

            //IAsyncResult: 异步操做接口(interface)
            //BeginInvoke: 委托(delegate)的一个异步方法的开始
            IAsyncResult result = handler.BeginInvoke(1, 2, null, null);

            Console.WriteLine("继续作别的事情。。。");

            //异步操做返回
            Console.WriteLine(handler.EndInvoke(result));
            Console.ReadKey();
        }
        
}

能够看到,主线程并无等待,而是直接向下运行了。 可是问题依然存在,当主线程运行到EndInvoke时,若是这时调用没有结束(这种状况极可能出现),这时为了等待调用结果,线程依旧会被阻塞。异步编程

异步委托,也能够参考以下写法:函数

Action<object> action=(obj)=>method(obj);
action.BeginInvoke(obj,ar=>action.EndInvoke(ar),null);

简简单单两句话就能够完成一部操做。this

异步回调

用回调函数,当调用结束时会自动调用回调函数,解决了为等待调用结果,而让线程依旧被阻塞的局面。spa

public class 异步回调
{
        static void Main()
        {
            Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法类.Add);

            //异步操做接口(注意BeginInvoke方法的不一样!)
            IAsyncResult result = handler.BeginInvoke(1,2,new AsyncCallback(回调函数),"AsycState:OK");
            
            Console.WriteLine("继续作别的事情。。。");
            Console.ReadKey();
        }

        static void 回调函数(IAsyncResult result)
        {      //result 是“加法类.Add()方法”的返回值

            //AsyncResult 是IAsyncResult接口的一个实现类,空间:System.Runtime.Remoting.Messaging
            //AsyncDelegate 属性能够强制转换为用户定义的委托的实际类。
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }
        
}

我定义的委托的类型为AddHandler,则为了访问 AddHandler.EndInvoke,必须将异步委托强制转换为 AddHandler。能够在异步回调函数(类型为 AsyncCallback)中调用 MAddHandler.EndInvoke,以获取最初提交的 AddHandler.BeginInvoke 的结果。.net

问题:

(1)int result = handler.Invoke(1,2); 为何Invoke的参数和返回值和AddHandler委托是同样的呢? 答: Invoke方法的参数很简单,一个委托,一个参数表(可选),而Invoke方法的主要功能就是帮助你在UI线程上调用委托所指定的方法。Invoke方法首先检查发出调用的线程(即当前线程)是否是UI线程,若是是,直接执行委托指向的方法,若是不是,它将切换到UI线程,而后执行委托指向的方法。无论当前线程是否是UI线程,Invoke都阻塞直到委托指向的方法执行完毕,而后切换回发出调用的线程(若是须要的话),返回。 因此Invoke方法的参数和返回值和调用他的委托应该是一致的。

(2)IAsyncResult result = handler.BeginInvoke(1,2,null,null);

BeginInvoke : 开始一个异步的请求,调用线程池中一个线程来执行, 返回IAsyncResult 对象(异步的核心). IAsyncResult 简单的说,他存储异步操做的状态信息的一个接口,也能够用他来结束当前异步。 注意: BeginInvoke和EndInvoke必须成对调用.即便不须要返回值,但EndInvoke仍是必须调用,不然可能会形成内存泄漏。

(3)IAsyncResult.AsyncState 属性: 获取用户定义的对象,它限定或包含关于异步操做的信息。 例如:

static void AddComplete(IAsyncResult result) {
AddHandler handler = (AddHandler)result.AsyncState;
Console.WriteLine(handler.EndInvoke(result)); 。。。。。 }

完整代码以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadCallback
{
    class Program
    {

        public delegate int AddHandler(int a, int b, int c);

        public class AddClass
        {
            public static int Add(int a, int b, int c)
            {
                Console.WriteLine("\n开始计算:" + a + "+" + b + "+"+c);
                Thread.Sleep(3000); //模拟该方法运行三秒
                Console.WriteLine("计算完成!");
                return a + b + c;
            }
        }

        /// <summary>
        /// 同步调用
        /// </summary>
        public class SynchronousCall
        {
            static void Main_S()
            {
                Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddClass.Add);
                int result = handler.Invoke(1, 2, 3);

                Console.WriteLine("继续作别的事情。。。");

                Console.WriteLine(result);
                Console.ReadKey();
            }

        }

        /// <summary>
        /// 异步调用
        /// </summary>
        public class AsynchronousCall
        {
            static void Main_S()
            {
                Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddClass.Add);

                //IAsyncResult: 异步操做接口(interface)
                //BeginInvoke: 委托(delegate)的一个异步方法的开始
                IAsyncResult result = handler.BeginInvoke(1, 2,3, null, null);
                Console.WriteLine("------继续作别的事情。。。\n");

                //异步操做返回
                Console.WriteLine(handler.EndInvoke(result));
                Console.ReadKey();
            }

        }


        static void Main(string[] args)
        {

            Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
            AddHandler handler = new AddHandler(AddClass.Add);

            //异步操做接口(注意BeginInvoke方法的不一样!)
            IAsyncResult result = handler.BeginInvoke(1, 2,3, new AsyncCallback(CallbackFunc), "AsycState:OK");

            Console.WriteLine("------继续作别的事情。。。--------");
            Console.ReadKey();

        }

        static void CallbackFunc(IAsyncResult result)
        {
            //result 是“加法类.Add()方法”的返回值             
            //AsyncResult 是IAsyncResult接口的一个实现类,引用空间:System.Runtime.Remoting.Messaging             
            //AsyncDelegate 属性能够强制转换为用户定义的委托的实际类。
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }  

    }
}

C#多线程回调传值例子

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System;
using System.Threading;
namespace DataImportFromAccess
{


    //声明一个回调函数:注意传递的参数要与Example类中的函数参数类型一致
    public delegate void ExampleCallback(int lineCount, Label lb);
    public class Form1{
        public Form1()
        {
            InitializeComponent();
        }

        public void CurrentNumber(int tempCurrent,Label lb)
        {
            lb.Text = tempCurrent.ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ThreadWithData twd = new ThreadWithData(1, 100,this.label1,new ExampleCallback(CurrentNumber));
            Thread td = new Thread(new ThreadStart(twd.RunMethod));
            td.Start();
        }   
        private void button2_Click(object sender, EventArgs e)
        {
            ThreadWithData twd = new ThreadWithData(2, 200,this.label2, new ExampleCallback(CurrentNumber));
            Thread td = new Thread(new ThreadStart(twd.RunMethod));
            td.Start();
        }
    }
    public class ThreadWithData
    {
        private int start = 0;
        private int end = 0;
        private ExampleCallback callBack;
        private Label lb;

        public ThreadWithData(int start,int end,Label lb,ExampleCallback callBack)
        {
            this.start = start;
            this.end = end;
            this.callBack=callBack;
            this.lb = lb;
        }
        public void RunMethod()
        {
            for(int i=start;i<end;i++)
            {
                Thread.Sleep(1000);
                if (callBack != null)
                    callBack(i,lb);
            }
         
        }
    }
}

引用: http://www.cnblogs.com/csMapx/archive/2011/06/21/2086054.html C#(同步调用、异步调用、异步回调) http://www.cnblogs.com/csMapx/archive/2011/06/21/2086054.html C#中的多线程使用 -- Thread 类: 使用回调函数从一个线程中检索数据 http://www.cnblogs.com/lvcy/archive/2012/06/15/2550061.html C#基础:线程之异步回调(委托)

相关文章: https://www.cnblogs.com/nevermore-wd/p/10565639.html 浅析C#中的Thread ThreadPool Task和async/await http://www.javashuo.com/article/p-fwybfswc-cy.html 剖析异步编程语法糖: async和await https://www.cnblogs.com/struggle999/p/6933376.html Thread,ThreadPool,Task, 到async await 的基本使用方法和理解 https://msdn.microsoft.com/zh-cn/magazine/jj991977.aspx 异步编译中的最佳作法 https://www.cnblogs.com/lsgsanxiao/p/5523282.html Invoke与BeginInvoke详解 http://www.javashuo.com/article/p-klvqlton-hw.html C# Task异步编程 https://www.cnblogs.com/xianyudotnet/p/5716908.html Async和await以及Task

相关文章
相关标签/搜索