zoukankan      html  css  js  c++  java
  • WinForm 进度条

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace LongTime
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            // 进度发生变化之后的回调方法
            private void workder_ValueChanged(object sender, Business.ValueEventArgs e)
            {
                System.Windows.Forms.MethodInvoker invoker = () =>
                    {
                        this.progressBar1.Value = e.Value;
                    };
    
                if (this.progressBar1.InvokeRequired)
                {
                    this.progressBar1.Invoke(invoker);
                }
                else
                {
                    invoker();
                }
            }
    
    
            private void button1_Click(object sender, EventArgs e)
            {
                // 禁用按钮
                this.button1.Enabled = false;
    
                // 实例化业务对象
                LongTime.Business.LongTimeWork workder = new Business.LongTimeWork();
    
                workder.ValueChanged += new Business.ValueChangedEventHandler(workder_ValueChanged);
    
                // 使用异步方式调用长时间的方法
                Action handler = new Action(workder.LongTimeMethod);
                handler.BeginInvoke(
                    new AsyncCallback(this.AsyncCallback),
                    handler
                    );
            }
    
            // 结束异步操作
            private void AsyncCallback(IAsyncResult ar)
            {
                // 标准的处理步骤
                Action handler = ar.AsyncState as Action;
                handler.EndInvoke(ar);
    
                MessageBox.Show("工作完成!");
    
                System.Windows.Forms.MethodInvoker invoker = () =>
                {
                    // 重新启用按钮
                    this.button1.Enabled = true;
                };
    
                if (this.InvokeRequired)
                {
                    this.Invoke(invoker);
                }
                else
                {
                    invoker();
                }
            }
    
        }
    }
    

      

    工作类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace LongTime.Business
    {
        // 定义事件的参数类
        public class ValueEventArgs 
            : EventArgs
        {
            public int Value { set; get;}
        }
    
        // 定义事件使用的委托
        public delegate void ValueChangedEventHandler( object sender, ValueEventArgs e);
    
        class LongTimeWork
        {
            // 定义一个事件来提示界面工作的进度
            public event ValueChangedEventHandler ValueChanged;
    
            // 触发事件的方法
            protected void OnValueChanged( ValueEventArgs e)
            {
                if( this.ValueChanged != null)
                {
                    this.ValueChanged( this, e);
                }
            }
    
            public void LongTimeMethod()
            {
                for (int i = 0; i < 15; i++)
                {
                    // 进行工作
                    System.Threading.Thread.Sleep(1000);
    
                    // 触发事件
                    ValueEventArgs e = new ValueEventArgs() { Value = i+1};
                    this.OnValueChanged(e);
                }
            }
        }
    }
    

      

     *********************************************

    一、C#线程概述

    在操作系统中一个进程至少要包含一个线程,然后,在某些时候需要在同一个进程中同时执行多项任务,或是为了提供程序的性能,将要执行的任务分解成多个子任务执行。这就需要在同一个进程中开启多个线程。我们使用C#编写一个应用程序(控制台或桌面程序都可以),然后运行这个程序,并打开windows任务管理器,这时我们就会看到这个应用程序中所含有的线程数,如下图所示。

    应用程序中所含有的线程数

    如果任务管理器没有“线程数”列,可以【查看】>【选择列】来显示“线程计数”列。从上图可以看出,几乎所有的进程都拥有两个以上的线程。从而可以看出,线程是提供应用程序性能的重要手段之一,尤其在多核CPU的机器上尤为明显。

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

    在C#中使用线程的方法很多,使用委托的BeginInvoke和EndInvoke方法就是其中之一。BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。我们可以通过四种方法从EndInvoke方法来获得返回值。

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

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

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

    namespace MyThread
    {
    class Program
    {
    private static int newTask(int ms)
    {
    Console.WriteLine("任务开始");
    Thread.Sleep(ms);
    Random random = new Random();
    int n = random.Next(10000);
    Console.WriteLine("任务完成");
    return n;
    }

    private delegate int NewTaskDelegate(int ms);


    static void Main(string[] args)
    {
    NewTaskDelegate task = newTask;
    IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);

    // EndInvoke方法将被阻塞2秒
    int result = task.EndInvoke(asyncResult);
    Console.WriteLine(result);
    }
    }
    }

    在运行上面的程序后,由于newTask方法通过Sleep延迟了2秒,因此,程序直到2秒后才输出最终结果(一个随机整数)。如果不调用EndInvoke方法,程序会立即退出,这是由于使用BeginInvoke创建的线程都是后台线程,这种线程一但所有的前台线程都退出后(其中主线程就是一个前台线程),不管后台线程是否执行完毕,都会结束线程,并退出程序。关于前台和后台线程的详细内容,将在后面的部分讲解。

    读者可以使用上面的程序做以下实验。首先在Main方法的开始部分加入如下代码:

    Thread.Sleep(10000);
    以使Main方法延迟10秒钟再执行下面的代码,然后按Ctrl+F5运行程序,并打开企业管理器,观察当前程序的线程数,假设线程数是4,在10秒后,线程数会增至5,这是因为调用BeginInvoke方法时会建立一个线程来异步执行newTask方法,因此,线程会增加一个。

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

    虽然上面的方法可以很好地实现异步调用,但是当调用EndInvoke方法获得调用结果时,整个程序就象死了一样,这样做用户的感觉并不会太好,因此,我们可以使用asyncResult来判断异步调用是否完成,并显示一些提示信息。这样做可以增加用户体验。代码如下:

    static void Main(string[] args)
    {
    NewTaskDelegate task = newTask;
    IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);

    while (!asyncResult.IsCompleted)
    {
    Console.Write("*");
    Thread.Sleep(100);
    }
    // 由于异步调用已经完成,因此, EndInvoke会立刻返回结果
    int result = task.EndInvoke(asyncResult);
    Console.WriteLine(result);
    }

    上面代码的执行结果如下图所示。

    执行结果

    由于是异步,所以“*”可能会在“任务开始”前输出,如上图所示。

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

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

    static void Main(string[] args)
    {
    NewTaskDelegate task = newTask;
    IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);

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

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

    以上介绍的就是C#线程中BeginInvoke和EndInvoke方法。

     *****************************************************

    C# Winform异步调用详解 (2010-12-29 10:47:30)转载▼
    标签: asynccallback iasyncresult asyncstate 异步调用 waithandle delegat 分类: C#/ASP.Net/VB.Net
    C#异步调用四大方法是什么呢?C#异步调用四大方法的使用是如何进行的呢?让我们首先了解下什么时候用到C#异步调用:
    .NET Framework 允许您C#异步调用任何方法。定义与您需要调用的方法具有相同签名的委托;公共语言运行库将自动为该委托定义具有适当签名的 BeginInvoke 和 EndInvoke 方法。
    BeginInvoke 方法用于启动C#异步调用。它与您需要异步执行的方法具有相同的参数,只不过还有两个额外的参数(将在稍后描述)。BeginInvoke 立即返回,不等待C#异步调用完成。BeginInvoke 返回 IasyncResult,可用于监视调用进度。
    EndInvoke 方法用于检索C#异步调用结果。调用 BeginInvoke 后可随时调用 EndInvoke 方法;如果C#异步调用未完成,EndInvoke 将一直阻塞到C#异步调用完成。EndInvoke 的参数包括您需要异步执行的方法的 out 和 ref 参数(在 Visual Basic 中为 ByRef 和 ByRef)以及由 BeginInvoke 返回的 IAsyncResult。
    注意:Visual Studio .NET 中的智能感知功能会显示 BeginInvoke 和 EndInvoke 的参数。如果您没有使用 Visual Studio 或类似的工具,或者您使用的是 C# 和 Visual Studio .NET,请参见异步方法签名获取有关运行库为这些方法定义的参数的描述。
    一.C#异步调用四大方法详解
    本主题中的代码演示了四种使用 BeginInvoke 和 EndInvoke 进行C#异步调用的常用方法。调用了 BeginInvoke 后,可以:
    · 进行某些操作,然后调用 EndInvoke 一直阻塞到调用完成。
    · 使用 IAsyncResult.AsyncWaitHandle 获取 WaitHandle,使用它的 WaitOne 方法将执行一直阻塞到发出 WaitHandle 信号,然后调用 EndInvoke。
    · 轮询由 BeginInvoke 返回的 IAsyncResult,确定C#异步调用何时完成,然后调用 EndInvoke。
    · 将用于回调方法的委托传递给 BeginInvoke。该方法在C#异步调用完成后在 ThreadPool 线程上执行,它可以调用 EndInvoke。
    警告:始终在C#异步调用完成后调用 EndInvoke。
    测试方法和异步委托
    四个示例全部使用同一个长期运行的测试方法 TestMethod。该方法显示一个表明它已开始处理的控制台信息,休眠几秒钟,然后结束。TestMethod 有一个 out 参数(在 Visual Basic 中为 ByRef),它演示了如何将这些参数添加到 BeginInvoke 和 EndInvoke 的签名中。您可以用类似的方式处理 ref 参数(在 Visual Basic 中为 ByRef)。
    下面的代码示例显示 TestMethod 以及代表 TestMethod 的委托;若要使用任一示例,请将示例代码追加到这段代码中。
    注意 为了简化这些示例,TestMethod 在独立于 Main() 的类中声明。或者,TestMethod 可以是包含 Main() 的同一类中的 static 方法(在 Visual Basic 中为 Shared)。
    using System;
    using System.Threading;

    public class AsyncDemo {
    // The method to be executed asynchronously.
    //
    public string TestMethod(
    int callDuration, out int threadId) {
    Console.WriteLine("Test method begins.");
    Thread.Sleep(callDuration);
    threadId = AppDomain.GetCurrentThreadId();
    return "MyCallTime was " + callDuration.ToString();
    }
    }

    // The delegate must have the same signature as the method
    // you want to call asynchronously.
    public delegate string AsyncDelegate(
    int callDuration, out int threadId);


    using System;
    using System.Threading;

    public class AsyncDemo {
    // The method to be executed asynchronously.
    //
    public string TestMethod(
    int callDuration, out int threadId) {
    Console.WriteLine("Test method begins.");
    Thread.Sleep(callDuration);
    threadId = AppDomain.GetCurrentThreadId();
    return "MyCallTime was " + callDuration.ToString();
    }
    }

    // The delegate must have the same signature as the method
    // you want to call asynchronously.
    public delegate string AsyncDelegate(
    int callDuration, out int threadId);
    0x01:C#异步调用四大方法之使用 EndInvoke 等待异步调用
    异步执行方法的最简单方式是以 BeginInvoke 开始,对主线程执行一些操作,然后调用 EndInvoke。EndInvoke 直到C#异步调用完成后才返回。这种技术非常适合文件或网络操作,但是由于它阻塞 EndInvoke,所以不要从用户界面的服务线程中使用它。
    public class AsyncMain {
    static void Main(string[] args) {
    // The asynchronous method puts the thread id here.
    int threadId;

    // Create an instance of the test class.
    AsyncDemo ad = new AsyncDemo();

    // Create the delegate.
    AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);

    // Initiate the asychronous call.
    IAsyncResult ar = dlgt.BeginInvoke(3000,
    out threadId, null, null);

    Thread.Sleep(0);
    Console.WriteLine("Main thread {0} does some work.",
    AppDomain.GetCurrentThreadId());

    // Call EndInvoke to Wait for
    //the asynchronous call to complete,
    // and to retrieve the results.
    string ret = dlgt.EndInvoke(out threadId, ar);

    Console.WriteLine("The call executed on thread {0},
    with return value "{1}".", threadId, ret);
    }
    }
    0x02:C#异步调用四大方法之使用 WaitHandle 等待异步调用
    等待 WaitHandle 是一项常用的线程同步技术。您可以使用由 BeginInvoke 返回的 IAsyncResult 的 AsyncWaitHandle 属性来获取 WaitHandle。C#异步调用完成时会发出 WaitHandle 信号,而您可以通过调用它的 WaitOne 等待它。
    如果您使用 WaitHandle,则在C#异步调用完成之后,但在通过调用 EndInvoke 检索结果之前,可以执行其他处理。
    public class AsyncMain {
    static void Main(string[] args) {
    // The asynchronous method puts the thread id here.
    int threadId;

    // Create an instance of the test class.
    AsyncDemo ad = new AsyncDemo();

    // Create the delegate.
    AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);

    // Initiate the asychronous call.
    IAsyncResult ar = dlgt.BeginInvoke(3000,
    out threadId, null, null);

    Thread.Sleep(0);
    Console.WriteLine("Main thread {0} does some work.",
    AppDomain.GetCurrentThreadId());

    // Wait for the WaitHandle to become signaled.
    ar.AsyncWaitHandle.WaitOne();

    // Perform additional processing here.
    // Call EndInvoke to retrieve the results.
    string ret = dlgt.EndInvoke(out threadId, ar);

    Console.WriteLine("The call executed on thread {0},
    with return value "{1}".", threadId, ret);
    }
    }
    0x03:C#异步调用四大方法之轮询异步调用完成
    您可以使用由 BeginInvoke 返回的 IAsyncResult 的 IsCompleted 属性来发现C#异步调用何时完成。从用户界面的服务线程中进行C#异步调用时可以执行此操作。轮询完成允许用户界面线程继续处理用户输入。
    public class AsyncMain {
    static void Main(string[] args) {
    // The asynchronous method puts the thread id here.
    int threadId;

    // Create an instance of the test class.
    AsyncDemo ad = new AsyncDemo();

    // Create the delegate.
    AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);

    // Initiate the asychronous call.
    IAsyncResult ar = dlgt.BeginInvoke(3000,
    out threadId, null, null);

    // Poll while simulating work.
    while(ar.IsCompleted == false) {
    Thread.Sleep(10);
    }

    // Call EndInvoke to retrieve the results.
    string ret = dlgt.EndInvoke(out threadId, ar);

    Console.WriteLine("The call executed on thread {0},
    with return value "{1}".", threadId, ret);
    }
    }
    0x04:C#异步调用四大方法之异步调用完成时执行回调方法
    如果启动异步调用的线程不需要处理调用结果,则可以在调用完成时执行回调方法。回调方法在 ThreadPool 线程上执行。
    要使用回调方法,必须将代表该方法的 AsyncCallback 委托传递给 BeginInvoke。也可以传递包含回调方法将要使用的信息的对象。例如,可以传递启动调用时曾使用的委托,以便回调方法能够调用 EndInvoke。
    public class AsyncMain {
    // Asynchronous method puts the thread id here.
    private static int threadId;

    static void Main(string[] args) {
    // Create an instance of the test class.
    AsyncDemo ad = new AsyncDemo();

    // Create the delegate.
    AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);

    // Initiate the asychronous call. Include an AsyncCallback
    // delegate reDIVsenting the callback method, and the data
    // needed to call EndInvoke.
    IAsyncResult ar = dlgt.BeginInvoke(3000,
    out threadId,
    new AsyncCallback(CallbackMethod),
    dlgt );

    Console.WriteLine("DIVss Enter to close application.");
    Console.ReadLine();
    }

    // Callback method must have the same signature as the
    // AsyncCallback delegate.
    static void CallbackMethod(IAsyncResult ar) {
    // Retrieve the delegate.
    AsyncDelegate dlgt = (AsyncDelegate) ar.AsyncState;

    // Call EndInvoke to retrieve the results.
    string ret = dlgt.EndInvoke(out threadId, ar);

    Console.WriteLine("The call executed on thread {0},
    with return value "{1}".", threadId, ret);
    }
    }

    二.C#异步调用四大方法的基本内容就向你介绍到这里,下面看有回调函数的WebRequest和WebResponse的异步操作。

    using System;
    using System.Net;
    using System.Threading;
    using System.Text;
    using System.IO;


    // RequestState 类用于通过
    // 异步调用传递数据
    public class RequestState
    {
    const int BUFFER_SIZE = 1024;
    public StringBuilder RequestData;
    public byte[] BufferRead;
    public HttpWebRequest Request;
    public Stream ResponseStream;
    // 创建适当编码类型的解码器
    public Decoder StreamDecode = Encoding.UTF8.GetDecoder();

    public RequestState()
    {
    BufferRead = new byte[BUFFER_SIZE];
    RequestData = new StringBuilder("");
    Request = null;
    ResponseStream = null;
    }
    }

    // ClientGetAsync 发出异步请求
    class ClientGetAsync
    {
    public static ManualResetEvent allDone = new ManualResetEvent(false);
    const int BUFFER_SIZE = 1024;

    public static void Main(string[] args)
    {

    if (args.Length < 1)
    {
    showusage();
    return;
    }

    // 从命令行获取 URI
    Uri HttpSite = new Uri(args[0]);

    // 创建请求对象
    HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(HttpSite);

    // 创建状态对象
    RequestState rs = new RequestState();

    // 将请求添加到状态,以便它可以被来回传递
    rs.Request = wreq;

    // 发出异步请求
    IAsyncResult r = (IAsyncResult)wreq.BeginGetResponse(new AsyncCallback(RespCallback), rs);

    // 将 ManualResetEvent 设置为 Wait,
    // 以便在调用回调前,应用程序不退出
    allDone.WaitOne();
    }

    public static void showusage()
    {
    Console.WriteLine("尝试获取 (GET) 一个 URL");
    Console.WriteLine(" 用法::");
    Console.WriteLine("ClientGetAsync URL");
    Console.WriteLine("示例::");
    Console.WriteLine("ClientGetAsync http://www.microsoft.com/net/");
    }

    private static void RespCallback(IAsyncResult ar)
    {
    // 从异步结果获取 RequestState 对象
    RequestState rs = (RequestState)ar.AsyncState;

    // 从 RequestState 获取 HttpWebRequest
    HttpWebRequest req = rs.Request;

    // 调用 EndGetResponse 生成 HttpWebResponse 对象
    // 该对象来自上面发出的请求
    HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(ar);

    // 既然我们拥有了响应,就该从
    // 响应流开始读取数据了
    Stream ResponseStream = resp.GetResponseStream();

    // 该读取操作也使用异步完成,所以我们
    // 将要以 RequestState 存储流
    rs.ResponseStream = ResponseStream;

    // 请注意,rs.BufferRead 被传入到 BeginRead。
    // 这是数据将被读入的位置。
    IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
    }


    private static void ReadCallBack(IAsyncResult asyncResult)
    {
    // 从 asyncresult 获取 RequestState 对象
    RequestState rs = (RequestState)asyncResult.AsyncState;

    // 取出在 RespCallback 中设置的 ResponseStream
    Stream responseStream = rs.ResponseStream;

    // 此时 rs.BufferRead 中应该有一些数据。
    // 读取操作将告诉我们那里是否有数据
    int read = responseStream.EndRead(asyncResult);

    if (read > 0)
    {
    // 准备 Char 数组缓冲区,用于向 Unicode 转换
    Char[] charBuffer = new Char[BUFFER_SIZE];

    // 将字节流转换为 Char 数组,然后转换为字符串
    // len 显示多少字符被转换为 Unicode
    int len = rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);
    String str = new String(charBuffer, 0, len);

    // 将最近读取的数据追加到 RequestData stringbuilder 对象中,
    // 该对象包含在 RequestState 中
    rs.RequestData.Append(str);


    // 现在发出另一个异步调用,读取更多的数据
    // 请注意,将不断调用此过程,直到
    // responseStream.EndRead 返回 -1
    IAsyncResult ar = responseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
    }
    else
    {
    if (rs.RequestData.Length > 1)
    {
    // 所有数据都已被读取,因此将其显示到控制台
    string strContent;
    strContent = rs.RequestData.ToString();
    Console.WriteLine(strContent);
    }

    // 关闭响应流
    responseStream.Close();

    // 设置 ManualResetEvent,以便主线程可以退出
    allDone.Set();
    }
    return;
    }
    }
    在这里有回调函数,且异步回调中又有异步操作。
    首先是异步获得ResponseStream,然后异步读取数据。
    这个程序非常经典。从中可以学到很多东西的。我们来共同探讨。
    总结
    上面说过,.net framework 可以异步调用任何方法。所以异步用处广泛。
    在.net framework 类库中也有很多异步调用的方法。一般都是已Begin开头End结尾构成一对,异步委托方法,外加两个回调函数和AsyncState参数,组成异步操作的宏观体现。所以要做异步编程,不要忘了委托delegate、Begin,End,AsyncCallBack委托,AsyncState实例(在回调函数中通过IAsyncResult.AsyncState来强制转换),IAsycResult(监控异步),就足以理解异步真谛了

    资源来自网络,分别为:
    http://www.cnblogs.com/ericwen/archive/2008/03/12/1101801.html
    http://developer.51cto.com/art/200908/145541.htm

  • 相关阅读:
    [ Docker ] 基础安装使用及架构
    [ Docker ] 基础概念
    Nginx
    ELK
    SVN + Jenkins 构建自动部署
    Zabbix
    ELK
    ELK 部署文档
    vue.js在visual studio 2017下的安装
    vue.js是什么
  • 原文地址:https://www.cnblogs.com/Charltsing/p/3738620.html
Copyright © 2011-2022 走看看