C#异步委托(小白笔记)

好久没有写笔记了,上传一个前段时间的写的东西,等到年的的时候,有时间把这段时间的笔记都上传了
异步与同步作比较,都是为了拿到结果,多线程我感觉不是为了拿到结果,是对CPU操作的,使这个进程拿到更多的线程来执行这个程序,多线程也有异步的说法吧;
小白笔记,欢迎指导-----------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _8.异步委托
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread:" + Thread.CurrentThread.ManagedThreadId);
            Func<int, int, string> fun = new Func<int, int, string>((a, b) => {
                Console.WriteLine("Delegate Thread:" + Thread.CurrentThread.ManagedThreadId);
                return (a + b).ToString(); });
            #region 异步简单的方式
            //string x= fun(3,4);//同步调用
            //异步调用委托
            //  IAsyncResult result=  fun.BeginInvoke(3, 4, null, null);//内部原理:使用了一个线程池的线程去执行了委托指向的方法
            //result.IsCompleted
            //endinvoke方法会阻塞当前的线程,直到异步委托指向完成之后,才能继续往下执行 
            //  string x=  fun.EndInvoke(result);
            #endregion

            #region 回调函数的异步委托
            //AsyncCallback
            //fun.BeginInvoke(5, 6, MyAsyncCallback, "123");1.传个参数
            fun.BeginInvoke(5, 6, MyAsyncCallback, fun);//2.直接把委托传过来

            #endregion
            //Console.WriteLine(x);
            Console.ReadKey();
        }
        //回调函数,是在异步委托执行完成之后,再来调回调函数
        static void MyAsyncCallback(IAsyncResult ar)
        {
            //1.拿到异步委托执行的结果
            //----------第一种传如参数
            //AsyncResult result = (AsyncResult)ar;
            //var del = (Func<int, int, string>)result.AsyncDelegate;
            //string x=  del.EndInvoke(result);
            //Console.WriteLine(x);
            //---------第二种直接传入一个委托
    
            var del = (Func<int, int, string>)ar.AsyncState;
           string x=  del.EndInvoke(ar);
            Console.WriteLine(x);
            //2.拿到给回调函数的参数
            //Console.WriteLine("拿到的异步委托的状态" + result.AsyncState);  

            Console.WriteLine("回调函数 Thread:" + Thread.CurrentThread.ManagedThreadId);
            
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值