异步Async

1.c#异步介绍

  异步必须基于委托,有委托才有异步

  新建一个window Form程序,添加一个按钮,(name)=btnAsync

using System;using System.Windows.Forms;
using System.Threading;
namespace MyAsync
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private delegate void DoSomethingHandler(string name);//定义一个委托函数
        private void btnAsync_Click(object sender, EventArgs e)
        {
            DoSomethingHandler method = new DoSomethingHandler(DoSomething);for (int i = 1; i <= 5; i++)
            {
                string name = string.Format("Async_{0}", i);
                method.BeginInvoke(name, null, null);//新建一个子线程,异步调用
            }
        }private void DoSomething(string name)//调用函数
        {
            Console.WriteLine("{0}正在执行,线程ID={1}", name, Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(1000);
            Console.WriteLine("{0}结束执行,线程ID={1}", name, Thread.CurrentThread.ManagedThreadId);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/wskxy/p/9209759.html