public static void EfFixed() { MyDelegate myDelegate = new MyDelegate(Update); var objDb = new EFHelp <TestInfors>().objectContext(); TestInfors tStart = new DbContext(objDb, true).Set <TestInfors>().Where(u => u.id == "1").FirstOrDefault(); DisplayProperty("【开始前】:", tStart); //重新新建修改1 TestInfors t1 = new TestInfors(); t1.id = "1"; t1.title = "55"; t1.contents = "内容"; //重新新建修改1 TestInfors t2 = new TestInfors(); t2.id = "1"; t2.title = "22"; t2.contents = "内容"; //执行并发操作 myDelegate.BeginInvoke(t1, null, null); myDelegate.BeginInvoke(t2, null, null); //最后 TestInfors tFinal = new DbContext(objDb, true).Set <TestInfors>().Where(u => u.id == "1").FirstOrDefault(); DisplayProperty("【开始前】:", tFinal); }
static void Main1(string[] args) { maxId = strartIndex - 1; for (int i = 0; i < count; i++) { lock (thisLock2) { maxId++; IAsyncResult result1 = myDelegate.BeginInvoke(maxId, Completed, null); } } Console.ReadKey(); }
private async Task CablePairDefaults() { using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText)) { //just good olfd status for now List <string> pairstatus = odw.GetDistinctDataColumn(CABLEPAIR_Table, "STATUS"); //class var del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "" && !uow.Query <CablePairStatus>().Select(x => x.StatusName).Contains(s))) { CablePairStatus cs = new CablePairStatus(uow) { StatusName = str }; uow.CommitChanges(); } } return(true); }); IAsyncResult classres = del.BeginInvoke(pairstatus, null, null); await Task.FromResult(pairstatus); } }
private void EjecutarDocumento() { try { FolderBrowserDialog folderDialog = new FolderBrowserDialog(); folderDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Reporte"; folderDialog.Description = "Seleccione la carpeta donde guardará el reporte"; folderDialog.ShowNewFolderButton = false; DialogResult accion = folderDialog.ShowDialog(); if (accion == DialogResult.OK) { progressBar.Value = 3; string rutaFolderDialog = $@"{folderDialog.SelectedPath}\Reporte [Detallado] {fechaIni.ToString("dd/MM/yyyy")} - {fechaFin.AddDays(-1).ToString("dd/MM/yyyy")}"; MyDelegate instance = new MyDelegate(CrearDocumento); instance.BeginInvoke(rutaFolderDialog, null, null); } else if (accion == DialogResult.Cancel) { progressBar.Visible = false; } } catch (Exception error) { log.Error($"Error: {error.Message}", error); MessageBox.Show($"Error: {error.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//static List<UserInfo> userInfoList = new List<UserInfo>(); static void Main(string[] args) { ThreadDemoClass demoClass = new ThreadDemoClass(); UserInfo userInfo = null; //创建一个委托并绑定方法 MyDelegate myDelegate = new MyDelegate(demoClass.Run); //创建一个回调函数的委托 AsyncCallback asyncCallback = new AsyncCallback(Complete); //回调函数的参数 string str = "I'm the parameter of the callback function!"; for (int i = 0; i < 3; i++) { userInfo = new UserInfo(); userInfo.Name = "Brambling" + i.ToString(); userInfo.Age = 33 + i; //传入参数并执行异步委托,并设置回调函数 IAsyncResult result = myDelegate.BeginInvoke(userInfo, asyncCallback, str); } Console.WriteLine("Main thread working..."); Console.WriteLine("Main thread ID is:" + Thread.CurrentThread.ManagedThreadId.ToString()); Console.WriteLine(); Console.ReadKey(); }
static void Main(string[] args) { int result; //往委托列表中添加方法 MyDelegate d = Add; //调用BeginInvoke 方法用于启动异步调用 Console.WriteLine("异步调用MyDelegate 开始"); //接受异步调用后的结果 IAsyncResult iar = d.BeginInvoke(123, 456, out result, null, null); //循环模拟其他操作,每隔500MS打一个 . 号 for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("."); } Console.WriteLine("等待"); //使用IAsyncResult.AsyncWaitHandle获取WaitHandle //使用WaitOne方法执行 阻塞等待 //异步调用完成时会发出WaitHandle信号,可通过WaitOne等待 iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("异步调用 Add()方法"); //使用EndInvoke方法检索异步调用结果 //EndInvoke方法:若异步调用未完成,EndInvoke将阻塞到异步调用完成 d.EndInvoke(out result, iar); //等待调用完成,输出结果 Console.WriteLine("异步调用 Add结果:{0}", result); }
static void Main(string[] args) { int result; MyDelegate d = Add;//创建委托实例 //调用BeginInvoke方法用于启动异步调用 Console.WriteLine("委托异步调用方法开始:"); IAsyncResult iar = d.BeginInvoke(123, 456, out result, null, null); Console.Write("执行其他操作"); for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("."); } Console.WriteLine("等待"); //使用IAsyncResult.AsyncWaitHandle获取WaitHandle,使用WaitOne方法执行 //阻塞等待,异步完成之时会发出WaitHandle信号,可通过WaitOne等待 iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("异步调用AsyncDelegate.Add()方法结束"); //EndInvoke方法:若异步调用未完成,EndInvoke将一直阻塞到异步调用完成 d.EndInvoke(out result, iar); Console.WriteLine("异步调用异步调用AsyncDelegate.Add()方法结果:{0}", result); Console.ReadKey(); }
static void Test(string[] args) { ThreadMessage("Main Thread"); //建立委托 MyDelegate myDelegate = new MyDelegate(Hello); //建立Person对象 Person person = new Person(); person.Name = "Elva"; person.Age = 27; //异步调用委托,输入参数对象person, 获取计算结果 myDelegate.BeginInvoke("Leslie", new AsyncCallback(Completed), person); //在启动异步线程后,主线程可以继续工作而不需要等待 for (int n = 0; n < 6; n++) { Console.WriteLine(" Main thread do work!"); } Console.WriteLine(""); Console.ReadKey(); }
private void Btn_Start_Click(object sender, EventArgs e) { MyDelegate myDelegate = new MyDelegate((string para) => { System.Diagnostics.Trace.WriteLine("delegate thread:" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); return(para.Length); }); IAsyncResult result = myDelegate.BeginInvoke("Leslie", null, null); System.Diagnostics.Trace.WriteLine("start invoke"); using (WebClient wc = new WebClient()) { Tb_ThreadInfo.Text = wc.DownloadString(new Uri("http://www.cnblogs.com")); System.Diagnostics.Trace.WriteLine("download ok:" + Tb_ThreadInfo.Text.Length); } System.Diagnostics.Trace.WriteLine("main thread:" + Thread.CurrentThread.ManagedThreadId); int data = myDelegate.EndInvoke(result); System.Diagnostics.Trace.WriteLine("result:" + data.ToString()); }
static void Main(string[] args) { MyDelegate myFun = TaskWhile; IAsyncResult result = myFun.BeginInvoke(1, 3000, null, null); while (!result.IsCompleted) { Console.Write("."); Thread.Sleep(50); } int i = myFun.EndInvoke(result); Console.WriteLine("异步委托返回结果是:{0}", i); MyDelegate myFun1 = TaskWhile; IAsyncResult result1 = myFun1.BeginInvoke(1, 2000, null, null); while (!result1.IsCompleted) { Console.Write("."); Thread.Sleep(50); } int j = myFun1.EndInvoke(result1); Console.WriteLine("异步委托返回结果是:{0}", j); }
static void Main(string[] args) { MyDelegate d = Square; System.Console.WriteLine("Thread-Id: {0}", Thread.CurrentThread.ManagedThreadId); IAsyncResult iar = d.BeginInvoke(12, null, null); while (!iar.IsCompleted) { System.Console.WriteLine("Blabla"); } int result = d.EndInvoke(iar); System.Console.WriteLine(result); // Process[] processList = Process.GetProcesses("."); // foreach(Process process in processList){ // System.Console.WriteLine("PID: {0}, Process-name: {1}", process.Id, process.ProcessName); // } // Process cal = Process.Start("cal"); // Thread.Sleep(5000); // cal.Kill(); }
private async Task AddressDefaults() { List <string> states = null; using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText)) { states = odw.GetListForDataColumn(@"select distinct state from subscribers where state is not null"); /// will be size|type|class if size is null 0, if type null then 'null' } //status var del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst .Where(s => s != "")) { if (!uow.Query <State>().Any(x => x.ShortName == str || x.LongName == str)) { State cs = new State(uow) { ShortName = str, LongName = str }; uow.CommitChanges(); } } return(true); } }); IAsyncResult stateres = del.BeginInvoke(states, null, null); await Task.FromResult(stateres); }
//【4】同时分发多个任务 private void btnExecute_Click(object sender, EventArgs e) { for (int i = 1; i <= 10; i++) { deteExecute.BeginInvoke(10 * i, 1000 * i, MyCallBack, i); } }
public void 基础() { //建立委托 MyDelegate myDelegate = new MyDelegate(Hello); //异步调用委托,获取计算结果 IAsyncResult result = myDelegate.BeginInvoke("Leslie", null, null); //在异步线程未完成前执行其他工作 while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 Console.WriteLine("Main thead do work!"); } //也可以使用WailHandle完成同样的工作,WaitHandle里面包含有方法WaitOne,与使用 IAsyncResult.IsCompleted 同样且更方便 while (!result.AsyncWaitHandle.WaitOne(200)) { Console.WriteLine("Main thead do work!"); } //等待异步方法完成,调用EndInvoke(IAsyncResult)获取运行结果 string data = myDelegate.EndInvoke(result); // EndInvoke执行完毕,取得之前传递的参数内容 string strState = (string)result.AsyncState; Console.WriteLine(data); }
// The thread procedure performs the task public void TX_Command_thread() { Console.WriteLine("comecei "); AsyncCallback cb = new AsyncCallback(MyCallBack); MyDelegate d = new MyDelegate(ss.RX_Command); while (!FlagStop) { Thread.Sleep(2000);//2 seconds try { Console.WriteLine("Trying to connect to: " + ClientProgram.AllServers[serverPos]); IAsyncResult ar = d.BeginInvoke(c, cb, null); Console.WriteLine("Connected to :" + ClientProgram.AllServers[serverPos]); } catch (System.Net.Sockets.SocketException e) { //Keep } //Thread.Sleep(60000);//2 seconds /* if (c.GetCommand().Equals("take") || c.GetCommand().Equals("remove")) * { * //If the command is Take. Send only one * Console.WriteLine("=======================================AQ"); * FlagStop = true; * }*/ } Console.WriteLine("Terminei de mandar para: " + ClientProgram.AllServers[serverPos]); }
private void button1_Click(object sender, EventArgs e) { //Task t = DoSomethingAsync(); //Task t = new Task(Test); //t.Start(); button1.Enabled = false; MyDelegate myDel = AsyncMethod; IAsyncResult rs = myDel.BeginInvoke(10000, null, null); while (!rs.IsCompleted) { //label1.Text = "..."; //Thread.Sleep(10); } string res = myDel.EndInvoke(rs); label1.Text = res; BeginInvoke(new MethodInvoker(delegate() { button1.Enabled = true; })); }
private void btn_asyncTest_Click(object sender, EventArgs e) { //Assign a function to the delegate myAsync = new MyDelegate(this.SomeFunction); myAsync.BeginInvoke(5, 10, null, null); }
static void Main(string[] args) { FibIt += FibonaciIteracja; FibRec += FibonaciRekurencja; SilniaIt += SilniaIteracja; SilniaRec += SilniaRekurencja; int value = 50; AutoResetEvent[] events = new AutoResetEvent[4]; for (int i = 0; i < 4; i++) { events[i] = new AutoResetEvent(false); } var res1 = FibIt.BeginInvoke(value, ThreadProc, new object[] { FibIt, "Fib iteracyjnie", events[0] }); var res2 = FibRec.BeginInvoke(value, ThreadProc, new object[] { FibRec, "Fib rekurencyjnie", events[1] }); var res3 = SilniaIt.BeginInvoke(10, ThreadProc, new object[] { SilniaIt, "Silnia iteracyjnie", events[2] }); var res4 = SilniaRec.BeginInvoke(10, ThreadProc, new object[] { SilniaRec, "Silnia rekurencja", events[3] }); WaitHandle.WaitAll(events); }
MyDelegate objCal = null;//ExecuteTask; //【4】同步执行多个任务 private void btnExecu_Click(object sender, EventArgs e) { for (int i = 1; i <= 10; i++) { objCal.BeginInvoke(10 * i, 1000 * i, MyCallback, i); } }
static void Main(string[] args) { deli = new MyDelegate(MyMethod); Console.WriteLine("Invoking the method..."); result = deli.BeginInvoke(MyMethodEnds, null); Console.WriteLine("Reached Console.ReadKey()"); Console.ReadKey(); }
private void button1_Click(object sender, EventArgs e) { MyDelegate add = new MyDelegate(Add); IAsyncResult addResult = add.BeginInvoke(5, 10, null, null); int result = add.EndInvoke(addResult); MessageBox.Show("5 + 10 = " + result); }
private void btn_asyncTest_Click(object sender, EventArgs e) { //Assign a function to the delegate myAsync = new MyDelegate(this.SomeFunction); myAsync.BeginInvoke(5, 10, null, null); }
/// <summary> /// BeginInvoke("刘备",23, new AsyncCallback(Completed), null)还有最后一个参数没用过的。那么最后一个参数是用来干什么 传参 /// 通过最一个参数对象,封装当前委托,就可以在回调函数直接调用EndInvoke执行结果 /// </summary> public void Process5() { MyDelegate myDelegate = new MyDelegate(GetString2); Person person = new Person(25, "参数老9", myDelegate); IAsyncResult result = myDelegate.BeginInvoke("张三", 25, new AsyncCallback(Completed5), person); //主线程可以继续工作而不需要等待 Console.WriteLine($"线程ID:{Thread.CurrentThread.ManagedThreadId},我是主线程,我干我的活,不再理你!"); }
/* * https://msdn.microsoft.com/en-us/library/system.delegate(v=vs.110).aspx * https://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.110).aspx */ static void Main1(string[] args) { MyDelegate mydelegate = new MyDelegate(HelloPeople); IAsyncResult result = mydelegate.BeginInvoke("chengzi", TestCallback, "Callback Param"); Console.WriteLine("========================"); Console.ReadKey(); }
static void Main(string[] args) { MyDelegate mydelegate = new MyDelegate(TestMethod); IAsyncResult result = mydelegate.BeginInvoke("abcdefg", TestCallBack, "hijklmn"); string resultstr = mydelegate.EndInvoke(result); Console.WriteLine(resultstr); Console.ReadKey(); }
static void Main(string[] args) { //3.实例化委托 MyDelegate m1 = new MyDelegate(MyFangfa); m1.BeginInvoke("hans", new AsyncCallback(MyCallBack), null); Console.ReadLine(); }
public void DoMyThing() { m_test = "Hi"; m_test2 = "Bye"; //create async call to do the work MyDelegate myDel = new MyDelegate(Execute); AsyncCallback cb = new AsyncCallback(CommandCallBack); IAsyncResult ar = myDel.BeginInvoke(cb, null); }
static void Main(string[] args) { MyDelegate mydelegate = new MyDelegate(TestdelMethod); IAsyncResult res = mydelegate.BeginInvoke("Thread param", TestCallBack, "callback param"); string resstr = mydelegate.EndInvoke(res); Console.WriteLine(resstr); Console.ReadKey(); }
static void Main(string[] args) { MyDelegate my = new MyDelegate(Add); AsyncCallback callback = new AsyncCallback(AddCompletion); IAsyncResult result = my.BeginInvoke(10, 20, callback, "qwerty"); int res = my.EndInvoke(result); Console.WriteLine("10 + 20 = " + res); Thread.Sleep(1000); }
private async Task WirecenterDefaults() { try { // Make //wirecentere types using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText)) { List <string> wctypes = odw.GetListForDataColumn("select distinct description from awirecenters where description is not null"); wctypes.Add(UNK); //type var del = new MyDelegate((lst) => { using (var uow = new UnitOfWork(Tsdl)) { foreach (var str in lst.Where(s => s != "")) { if (!uow.Query <WirecenterType>().Any(x => x.TypeName == str)) { WirecenterType cs = new WirecenterType(uow) { TypeName = str, TypeDescription = str }; uow.CommitChanges(); } } } return(true); }); IAsyncResult typeres = del.BeginInvoke(wctypes, null, null); using (var uow = new UnitOfWork(Tsdl)) { Wirecenter wc = uow.Query <Wirecenter>().FirstOrDefault(x => x.LocationName == UNK || x.CLLI == UNK); if (wc == null) { wc = new Wirecenter(uow) { LocationName = UNK, CLLI = UNK, Type = uow.Query <WirecenterType>().FirstOrDefault(x => x.TypeName == UNK) }; uow.CommitChanges(); } } await Task.FromResult(typeres); } } catch (Exception ex) { MessageBox.Show("" + ex); } }
public static void Main(string[] args) { //在更新数据前显示对象信息 PersonDAL personDAL = new PersonDAL(); var beforeObj = personDAL.GetPerson(1); personDAL.DisplayProperty("Before", beforeObj); //更新Person的FirstName、SecondName属性 Person person1 = new Person(); person1.Id = 1; person1.FirstName = "Mike"; person1.SecondName = "Wang"; person1.Age = 32; person1.Address = "Tianhe"; person1.Tel = "13660123456"; person1.Email = "*****@*****.**"; //更新Person的FirstName、SecondName属性 Person person2 = new Person(); person2.Id = 1; person2.FirstName = "Rose"; person2.SecondName = "Chen"; person2.Age = 32; person2.Address = "Tianhe"; person2.Tel = "13660123456"; person2.Email = "*****@*****.**"; //使用异步方式更新数据 MyDelegate myDelegate = new MyDelegate(personDAL.Update); myDelegate.BeginInvoke(person1, null, null); myDelegate.BeginInvoke(person2, null, null); //显示完成更新后数据源中的对应属性 Thread.Sleep(1000); var afterObj = personDAL.GetPerson(1); personDAL.DisplayProperty("After", afterObj); Console.ReadKey(); }
static void Main () { //przypisujemy do instancji metodę fin = func; //wywołujemy ją z parametrem x=1024, najpierw się zaczynają parametry metody fin.BeginInvoke (1024, new AsyncCallback (Callback), fin); //czekamy Console.ReadKey (); }
/// <summary> /// 文件下载方式 /// </summary> /// <param name="args"></param> static void Main1(string[] args) { httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(7); strs = File.ReadAllLines("F://1/我的小说网.txt").ToList(); endIndex = strs.Count; // Console.WriteLine(endIndex); maxId = strartIndex - 1; for (int i = 0; i < count; i++) { lock (thisLock2) { maxId++; IAsyncResult result1 = myDelegate.BeginInvoke(maxId, Completed, null); } } Console.ReadKey(); }
static void Main () { //przypisujemy do delegaty metodę fin = func; //wywołujemy ją kilka razy for(int i=0;i<10;i++) fin.BeginInvoke (new AsyncCallback(Callback), fin); //czekamy Console.ReadKey (); }
public static void Main(string[] args) { //在更新数据前显示对象信息 PersonDAL personDAL = new PersonDAL(); var beforeObj = personDAL.GetPerson(24); personDAL.Display("Before", beforeObj); //更新Person的SecondName,Age两个属性 Person person1 = new Person(); person1.Id = 24; person1.FirstName = "Leslie"; person1.SecondName = "Wang"; person1.Age = 32; person1.Address = "Tianhe"; person1.Telephone = "13660123456"; person1.EMail = "*****@*****.**"; //更新Person的FirstName属性 Person person2 = new Person(); person2.Id = 24; person2.FirstName = "Rose"; person2.SecondName = "Lee"; person2.Age = 34; person2.Address = "Tianhe"; person2.Telephone = "13660123456"; person2.EMail = "*****@*****.**"; //使用异步方式同时更新数据 MyDelegate myDelegate = new MyDelegate(personDAL.Update); myDelegate.BeginInvoke(person1, null, null); myDelegate.BeginInvoke(person2, null, null); Thread.Sleep(300); //在更新数据后显示对象信息 var afterObj = personDAL.GetPerson(24); personDAL.Display("After", afterObj); Console.ReadKey(); }
static void Main(string[] args) { MyDelegate asyncCall = new MyDelegate(Sum); Console.WriteLine("Starting method async."); IAsyncResult status = asyncCall.BeginInvoke(5, 6, null, null); Console.WriteLine("Async method is working"); Console.WriteLine("Calling EndInvoke()"); int result = asyncCall.EndInvoke(status); Console.WriteLine("EndInvoke() returned"); Console.WriteLine("Result={0}", result); }
//异步传输信息 public static bool TransMsg_Async(string msg) { if (! AllowRemoteOperation) { return false; } //On Error Goto Errorhandler VBConversions Warning: On Error Goto not supported in C# string clientname; clientname = "qiantai"; //返回当前电脑名称 //判断代理是否被创建 if (svrobj == null) { //引发错误 //Err.Raise(8000, MessageBox.Show("无法创建代理"); return false; } //代理创建成功 AsyncCallback cb; cb = new AsyncCallback(MyCallBack); MyDelegate d; d = new MyDelegate(svrobj.AddtoMsgQue); IAsyncResult ar; ar = d.BeginInvoke(msg, cb, 0); MessageBox.Show("成功"); return true; }
public void LaunchUpdate(bool forceRefresh) { _forceUsageRefresh = forceRefresh; IsWorking = true; Account.Account.BeginEdit(); BrowserException = null; btnUpdate.IsEnabled = false; btnAdvancedStats.IsEnabled = false; btnSendMail.IsEnabled = false; // Si la BD n'existe pas, on la crée if (DataBaseFactory.Instance.IsAvailable && !DataBaseFactory.Instance.TableExist(Account.Account.Username)) DailyUsageDAO.Instance.CreateTable(Account.Account.Username); MyDelegate ad = new MyDelegate(UpdateClient); ad.BeginInvoke(new AsyncCallback(UpdateClientComplete), null); }
public override void ShowUsage() { ThreadMessage("Main Thread"); //创建委托 MyDelegate myDelegate = new MyDelegate(Hello); //如果在使用myDelegate.BeginInvoke后立即调用myDelegate.EndInvoke,在异步线程未完成工作以前主线程将处于阻塞状态,等到异步线程结束获取计算结果后,主线程才能继续工作,这明显无法展示出多线程的优势。此时可以好好利用IAsyncResult 提高主线程的工作性能 Console.WriteLine("请选择使用何种方式发起异步线程未完成状态的判断?"); Console.WriteLine("1):轮询IsCompleted 2):WaitOne 3)WaiAll 4)回调函数"); //在异步线程未完成前执行其他工作 ConsoleKeyInfo key = Console.ReadKey(true); //记录开始任务时的时间 DateTime startWorkTime = DateTime.Now; if (key.Key == ConsoleKey.D1 || key.Key == ConsoleKey.D2 || key.Key == ConsoleKey.D3) { //异步调用委托,获取计算结果 IAsyncResult result = myDelegate.BeginInvoke("Frost", null, null); switch (key.Key) { #region 1、轮询result.IsCompleted属性 case ConsoleKey.D1: while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion #region 2、WaitOne属性判断 //除此以外,也可以使用WailHandle完成同样的工作,WaitHandle里面包含有一个方法WaitOne(int timeout),它可以判断委托是否完成工作,在工作未完成前主线程可以继续其他工作。运行下面代码可得到与使用 IAsyncResult.IsCompleted 同样的结果,而且更简单方便 。 case ConsoleKey.D2: while (!result.AsyncWaitHandle.WaitOne(200)) { TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion #region 3、WaitAll属性判断 //当要监视多个运行对象的时候,使用IAsyncResult.WaitHandle.WaitOne可就派不上用场了。 //幸好.NET为WaitHandle准备了另外两个静态方法:WaitAny(waitHandle[], int)与WaitAll (waitHandle[] , int)。 //其中WaitAll在等待所有waitHandle完成后再返回一个bool值。 //而WaitAny是等待其中一个waitHandle完成后就返回一个int,这个int是代表已完成waitHandle在waitHandle[]中的数组索引。 //下面就是使用WaitAll的例子,运行结果与使用 IAsyncResult.IsCompleted 相同。 //等待异步方法完成,调用EndInvoke获取运行结果 case ConsoleKey.D3: //加入所有检测对象 WaitHandle[] waitList = new WaitHandle[] { result.AsyncWaitHandle }; while (!WaitHandle.WaitAll(waitList, 200)) { TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("Work has being doing for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion } string data = myDelegate.EndInvoke(result); Console.WriteLine(data); } else if (key.Key == ConsoleKey.D4) { #region 4、回调函数 //使用轮询方式来检测异步方法的状态非常麻烦,而且效率不高,有见及此,.NET为 IAsyncResult BeginInvoke(AsyncCallback , object)准备了一个回调函数。使用 AsyncCallback 就可以绑定一个方法作为回调函数,回调函数必须是带参数 IAsyncResult 且无返回值的方法: void AsycnCallbackMethod(IAsyncResult result) 。在BeginInvoke方法完成后,系统就会调用AsyncCallback所绑定的回调函数,最后回调函数中调用 XXX EndInvoke(IAsyncResult result) 就可以结束异步方法,它的返回值类型与委托的返回值一致。 //建立Person对象,用作参数 Person person = new Person(); person.Name = "Elva"; person.Age = 27; //第一个参数为委托方法对应的参数,第二个为回调函数,第三个为传入的参数 IAsyncResult result = myDelegate.BeginInvoke("Frost", new AsyncCallback(Completed), person); while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } //可以看到,主线在调用BeginInvoke方法可以继续执行其他命令,而无需再等待了,这无疑比使用轮询方式判断异步方法是否完成更有优势。 //在异步方法执行完成后将会调用AsyncCallback所绑定的回调函数,注意一点,回调函数依然是在异步线程中执行,这样就不会影响主线程的运行,这也使用回调函数最值得青昧的地方。 //在回调函数中有一个既定的参数IAsyncResult,把IAsyncResult强制转换为AsyncResult后,就可以通过 AsyncResult.AsyncDelegate 获取原委托,再使用EndInvoke方法获取计算结果。 #endregion } Console.ReadKey(); }