异步回调--BeginInvoke方法
开始和结束异步操作(xxx表示同步方法的名词):Beginxxx和Endxxx
例如:FileStream类的对象的BeginRead()和EndRead()
BeginRead()方法返回一个IAsyncResult对象,表示异步操作的状态。如果喜欢阻塞当前线程并等待读取完成,那么可以调用EndRead()方法,并将IAsyncResult对象作为参数传递给该方法。
BeginRead()方法实际就是启动一个新线程来进行异步读取,而EndRead()方法相当与调用了异步线程的Join方法。
demo1:创建10个异步线程,每个线程负责读取10个字节到缓冲区中,而回调方法GetPosition在每个线程结束后都会被调用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace AsyncCallback { class Program { static void Main(string[] args) { using (FileStream fs = new FileStream(@"F:\\123.txt", FileMode.Open, FileAccess.Read)) { byte[] bs = new byte[1000]; for (int i = 0; i < 10; i++) { fs.BeginRead(bs, i * 100, 100, GetPosition, fs); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.Append((char)i); } Console.ReadKey(); } } static void GetPosition(IAsyncResult iar) { FileStream fs = (FileStream)iar.AsyncState; Console.WriteLine("本次读取文件文职:{0}",fs.Position); fs.EndRead(iar); } } }
demo2:delegate委托的BeginInvoke、EndInvoke、AsyncCallback用法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace BeginInvoke { class Program { static void Main(string[] args) { NewTaskDelegate task = NewTask; //int n = task(2000); //AsyncCallback方法一 //AsyncCallback callback = new AsyncCallback(MyAsyncCallback); //IAsyncResult asyncResult = task.BeginInvoke(2000, callback, task); //AsyncCallback方法二 IAsyncResult asyncResult = task.BeginInvoke(2000, MyAsyncCallback, task); //int result = task.EndInvoke(asyncResult); //Console.WriteLine(result); Console.ReadKey(); } public delegate int NewTaskDelegate(int ms); private static int NewTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random r = new Random(); int n = r.Next(10000); Console.WriteLine("任务完成"); return n; } private static void MyAsyncCallback(IAsyncResult iar) { NewTaskDelegate task = (NewTaskDelegate)iar.AsyncState; int n = task.EndInvoke(iar); Console.WriteLine(n); Console.WriteLine("异步结束。"); } } }