首页 > 代码库 > C#异步和委托

C#异步和委托

 技术分享

以上两种显示方法都实现返回值写法,无返回值两种方法基本无区别。

由执行时间结果看出,异步可以直接结束主线程,方法也不需要主线程处理过多的代码。

委托需要在主线程编写代码,并且写法有些复杂。

using System;using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncAwait
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btclear_Click(object sender, EventArgs e)
        {
            tbshow.Text = "";
        }
        private void showMsg(string sMsg)
        {
            tbshow.Text += Thread.CurrentThread.ManagedThreadId + sMsg + DateTime.Now.ToString() + "\r\n";
        }

        private void btRun_Click(object sender, EventArgs e)
        {
            //异步,分线程处理,多次点击,还可以等待返回结果。
            asyncTask();
            showMsg("btRun_asyncTaskClick.end..");
        }
        public async void asyncTask()
        {
            string x = await asyncTask2();
            showMsg(x);
            Thread.Sleep(1000);
            showMsg("asyncTask.end");
        }
        public async Task<string> asyncTask2()
        {
            return await Task.Run(() =>
            {
                //模拟一个超大工作量的进程
                showMsg("run..BeginInvoke.start.");
                Random rd = new Random();
                Thread.Sleep(rd.Next(3000, 6000));
                showMsg("run..BeginInvoke.end.");
                return "返回值:asyncTask2End" + DateTime.Now.ToString();
            });
        }
        public delegate void MainFun(string a,out string b);
        private void btInvoke_Click(object sender, EventArgs e)
        {
            string sReturn = "";
            //委托当执行EndInvoke时,线程被锁死了,无法多次点击
            MainFun myMainFun = new MainFun(BeginInvoke);
            IAsyncResult myIAsyncResult = myMainFun.BeginInvoke("a", out sReturn, null, null);
            myMainFun.EndInvoke(out sReturn,myIAsyncResult);
            showMsg(sReturn);
            Thread.Sleep(1000);
            showMsg("runInvoke.end..");
        }
        public void BeginInvoke(string a,out string b)
        {
            //模拟一个超大工作量的进程
            showMsg("run..BeginInvoke.start.");
            Random rd = new Random();
            Thread.Sleep(rd.Next(3000, 6000));
            showMsg("run..BeginInvoke.end.");
            b = "返回值:BeginInvokeEnd" + DateTime.Now.ToString();
        }

        private void btrun2_Click(object sender, EventArgs e)
        {
            string sReturn = "";
            BeginInvoke("a",out sReturn);
            showMsg("run.end..");
        }
    }
}

 

C#异步和委托