委托同步执行与异步执行

http://www.cnblogs.com/luxiaoxun/p/3280146.html

http://developer.51cto.com/art/200908/141587.htm

http://www.cnblogs.com/stg609/p/4050483.html

http://www.cnblogs.com/stg609/p/4052015.html

委托同步顺序执行:Invoke

TestClass tc = new TestClass();
//无参数,返回string类型
Func<int, string> method = n => tc.TestThread2(n);

method.Invoke(10);

用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程

BeginInvoke方法可以使用线程异步地执行委托所指向的方法。

然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。

我们可以通过四种方法来获得返回值。

直接使用EndInvoke方法来获得返回值

当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕。如下面的代码所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public delegate string MyDelegate(object data);
    public class AsyncTest
    {
        public static void Test()
        {
            MyDelegate mydelegate = new MyDelegate(TestMethod);
            //BeginInvoke的三个参数:1.委托说指向的函数的参数  2.回调函数名称  3.回调函数的参数
            IAsyncResult result = mydelegate.BeginInvoke("my name is jay!", TestCallback, "Callback Param");

            //异步执行完成,阻塞5秒
            string resultstr = mydelegate.EndInvoke(result);
            Console.WriteLine(resultstr);
        }

        //线程函数
        public static string TestMethod(object data)
        {
            Thread.Sleep(5000);//延迟,阻塞5秒,然后执行 EndInvoke
            string datastr = data as string;
            return "线程参数:" + datastr;
        }

        //异步回调函数
        public static void TestCallback(IAsyncResult data)
        {
            Console.WriteLine("回调函数输出:" + data.AsyncState);
        }
    }
}

在运行上面的程序后,由于TestMethod方法通过Sleep延迟了5秒,因此,程序直到5秒后才输出最终结果。

如果不调用EndInvoke方法,程序会立即退出,这是由于使用BeginInvoke创建的线程都是后台线程,这种线程一但所有的前台线程都退出后(其中主线程就是一个前台线程),不管后台线程是否执行完毕,都会结束线程,并退出程序。

关于前台和后台线程的详细内容,将在后面的部分讲解。

使用IAsyncResult asyncResult属性来判断异步调用是否完成

public static void Test2()
        {
            MyDelegate task = new MyDelegate(TestMethod);
            IAsyncResult asyncResult = task.BeginInvoke("my name is jay!", null, null);
            //判断是否完成
            while (!asyncResult.IsCompleted)
            {
                Console.Write("*");
                Thread.Sleep(100);
            }
            // 由于异步调用已经完成,因此, EndInvoke会立刻返回结果  
            string result = task.EndInvoke(asyncResult);
            Console.WriteLine(result);
        }

使用WaitOne方法等待异步方法执行完成

使用WaitOne方法是另外一种判断异步调用是否完成的方法。代码如下:

public static void Test3()
        {
            MyDelegate task = new MyDelegate(TestMethod);
            IAsyncResult asyncResult = task.BeginInvoke("my name is jay!", null, null);

            while (!asyncResult.AsyncWaitHandle.WaitOne(100, false))
            {
                Console.Write("*");
            }

            string result = task.EndInvoke(asyncResult);
            Console.WriteLine(result);
        }

WaitOne的第一个参数表示要等待的毫秒数,在指定时间之内,WaitOne方法将一直等待,直到异步调用完成,并发出通知,WaitOne方法才返回true。

当等待指定时间之后,异步调用仍未完成,WaitOne方法返回false,如果指定时间为0,表示不等待,如果为-1,表示永远等待,直到异步调用完成。

使用回调方式返回结果

上面介绍的几种方法实际上只相当于一种方法。这些方法虽然可以成功返回结果,也可以给用户一些提示,但在这个过程中,整个程序就象死了一样(如果读者在GUI程序中使用这些方法就会非常明显),要想在调用的过程中,程序仍然可以正常做其它的工作,就必须使用异步调用的方式。下面我们使用GUI程序来编写一个例子,代码如下:

private delegate int MyMethod();
        private int method()
        {
            Thread.Sleep(10000);
            return 100;
        }
        //回调函数,参数须是IAsyncResult
        private void MethodCompleted(IAsyncResult asyncResult)
        {
            if (asyncResult == null) return;
            TextBox1.Text = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult).ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //使用委托开始一个异步线程
            MyMethod my = method;
            //开启一个线程,执行my指向的函数
            //线程执行完毕,将返回状态作为参数 传递给回调函数MethodCompleted
            //MethodCompleted的参数须是IAsyncResult
            IAsyncResult asyncResult = my.BeginInvoke(MethodCompleted, my);
        }

要注意的是,这里使用了BeginInvoke方法的最后两个参数(如果被调用的方法含有参数的话,这些参数将作为BeginInvoke的前面一部分参数,如果没有参数,BeginInvoke就只有两个参数了)。第一个参数是回调方法委托类型,这个委托只有一个参数,就是IAsyncResult,如MethodCompleted方法所示。当method方法执行完后,系统会自动调用MethodCompleted方法。BeginInvoke的第二个参数需要向MethodCompleted方法中传递一些值,一般可以传递被调用方法的委托,如上面代码中的my。这个值可以使用IAsyncResult.AsyncState属性获得。

由于上面的代码通过异步的方式访问的form上的一个textbox,因此,需要按ctrl+f5运行程序(不能直接按F5运行程序,否则无法在其他线程中访问这个textbox,关于如果在其他线程中访问GUI组件,并在后面的部分详细介绍)。并在form上放一些其他的可视控件,然在点击button1后,其它的控件仍然可以使用,就象什么事都没有发生过一样,在10秒后,在textbox1中将输出100。

其他组件的BeginXXX和EndXXX方法

在其他的.net组件中也有类似BeginInvoke和EndInvoke的方法,如System.Net.HttpWebRequest类的BeginGetResponse和EndGetResponse方法,下面是使用这两个方法的一个例子:

private void requestCompleted(IAsyncResult asyncResult)
        {
            if (asyncResult == null) { return; }
            System.Net.HttpWebRequest hwr = asyncResult.AsyncState as System.Net.HttpWebRequest;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)hwr.EndGetResponse(asyncResult);
            using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
            {
                TextBox1.Text = sr.ReadToEnd();
            }
        }

        private delegate System.Net.HttpWebResponse RequestDelegate(System.Net.HttpWebRequest request);
     //异步请求
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.cnblogs.com");
            IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);
        }
原文地址:https://www.cnblogs.com/xsj1989/p/5265444.html