好久没有写笔记了,上传一个前段时间的写的东西,等到年的的时候,有时间把这段时间的笔记都上传了
异步与同步作比较,都是为了拿到结果,多线程我感觉不是为了拿到结果,是对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);
}
}
}