c#中两种常用的异步调用方法

       异步调用其实就是对线程的一种应用,但异步调用在使用上更加灵活,而且功能更强大。此外,异步调用还有一个的优点就是调用的是线程池里的线程(c#开发的应用程序的线程池里默认的线程数是25,如果要求调用线程池里的线程,而池里面的线程都是在使用的状态下时,外部请求会被放到一个队列里进行排队,等池里有空闲的线程时请求才被执行),开发者不用担心如何管理池里面的线程,直接调用即可。
        下面列出两种最常用的异步调用的用法
一、没有回调函数的用法
        定义委托:
         private delegate void Asynchronism(List<string> list);
         //调用
         private void simpleButton1_Click(object sender, EventArgs e)
        {  //实例化一个委托,开发中要传几个、什么类型的参数,在定义委托时就要指定好参数
            Asynchronism Amethod = new Asynchronism(AsynchronismPrint);
           //第一个参数是定义委托时定义好的参数及类型,第二个参数是要执行的回调函数,第三个是要参给回调函数的参数
            IAsyncResult iresult= Amethod.BeginInvoke(m_alist, null,null);
           //这一句作用是结束异步调用,可以放在异步调用之后的任务位置,但这种写法会引起主线程的阻塞,等异步调用执行完成后再继续往下执行
          Amethod.EndInvoke(iresult);  
          //在主程序时执行的方法体
          ...
         SynchronismPrint(m_list);
        }
        /// <summary>
        /// 异步执行的方法:把传进来的列表里的数据打印出来
        /// </summary>
        /// <param name="list"></param>
        private void AsynchronismPrint(List<string> list)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Asynchronism(AsynchronismPrint), new object[] { list });
                return;
            }
            listBoxControl1.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl1.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
        }
        /// <summary>
        /// 主程序里执行的方法,作用是用来测试看是否与异步调用的方法同时执行
        /// </summary>
        /// <param name="list"></param>
        private void SynchronismPrint(List<string> list)
        {
            listBoxControl2.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl2.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
        }
二、带回调函数的用法
       private void simpleButton1_Click(object sender, EventArgs e)
        {  //实例化一个委托,开发中要传几个、什么类型的参数,在定义委托时就要指定好参数
            Asynchronism Amethod = new Asynchronism(AsynchronismPrint);
           //实例化一个回调对象
           AsyncCallback Acall = new AsyncCallback(Acallback);
          //第三个参数提定了传给回调函数的参数,这是一个object类型,虽然只能传一个参数给回调函数,但可以传任类型的对象
            Amethod.BeginInvoke(m_alist, Acall, Amethod);
          //在主程序时执行的方法体
          SynchronismPrint(m_list);
        }
       
        /// <summary>
        /// 异步执行的方法
        /// </summary>
        /// <param name="list"></param>
        private void AsynchronismPrint(List<string> list)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Asynchronism(AsynchronismPrint), new object[] { list });
                return;
            }
            listBoxControl1.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl1.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
           
        }
        /// <summary>
        /// 回调函数,有且只有一个参数,但该参数可以传任何类型的object,通过异步调用时指定参数:Amethod.BeginInvoke(m_alist, Acall, Amethod);
        /// </summary>
        /// <param name="iAresult"></param>
        private void Acallback(IAsyncResult iAresult)
        {
            //取得传入参数
            Asynchronism result = iAresult.AsyncState as Asynchronism;
            //结束回调调用
            result.EndInvoke(iAresult);

        }
        /// <summary>
        /// 主程序里执行的方法,作用是用来测试看是否与异步调用的方法同时执行
        /// </summary>
        /// <param name="list"></param>
        private void SynchronismPrint(List<string> list)
        {
            listBoxControl2.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl2.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
        }

注:以下是测试实例的全部代码,在vs2008下运行通过
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 asynchronism
{
    public partial class Form1 : Form
    {
        private List<string> m_alist = new List<string>();
        private List<string> m_list = new List<string>();

        private delegate void Asynchronism(List<string> list);

        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 1000; i++)
            {
                m_alist.Add("AS"+i.ToString());
            }
            for (int j= 0; j < 1000; j++)
            {
                m_list.Add("S" + j.ToString());
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Asynchronism Amethod = new Asynchronism(AsynchronismPrint);
            AsyncCallback Acall = new AsyncCallback(Acallback);
            Amethod.BeginInvoke(m_alist, Acall, Amethod);
            //IAsyncResult iresult= Amethod.BeginInvoke(m_alist, null,null);
            //labelControl3.Text = DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString();
            //Amethod.EndInvoke(iresult);
            SynchronismPrint(m_list);
           
        }
        /// <summary>
        /// 异步执行的方法
        /// </summary>
        /// <param name="list"></param>
        private void AsynchronismPrint(List<string> list)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Asynchronism(AsynchronismPrint), new object[] { list });
                return;
            }
            listBoxControl1.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl1.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
           
        }
        /// <summary>
        /// 回调函数,有且只有一个参数,但该参数可以传任何类型的object,通过异步调用时指定参数:Amethod.BeginInvoke(m_alist, Acall, Amethod);
        /// </summary>
        /// <param name="iAresult"></param>
        private void Acallback(IAsyncResult iAresult)
        {
            //取得传入参数
            Asynchronism result = iAresult.AsyncState as Asynchronism;
            //结束回调调用
            result.EndInvoke(iAresult);

        }
        /// <summary>
        /// 主程序里执行的方法,作用是用来测试看是否与异步调用的方法同时执行
        /// </summary>
        /// <param name="list"></param>
        private void SynchronismPrint(List<string> list)
        {
            listBoxControl2.Items.Clear();
            foreach (string s in list)
            {
                listBoxControl2.Items.Add(DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "->" + s);
                Application.DoEvents();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值