/// <summary> /// 异步方法 /// </summary> public static void AsyncAdvanced() { Console.WriteLine("*******AsyncAdvanced********"); string str = string.Format("Async-{0}", 1); Delegate method = DoSomething; //第一个参数为委托的参数,第二个参数为异步执行完成后的回调,第三个参数是用户定义的对象(AsyncState) AsyncCallback callback = t => Console.WriteLine("这里是AsyncCallback,当前线程ID={0}", Thread.CurrentThread.ManagedThreadId, t.AsyncState); IAsyncResult result = method.BeginInvoke(str, callback, "dsh"); #region 异步等待(让主线程等待) //方式一(一直等到结束) result.AsyncWaitHandle.WaitOne(-1); //方式二(此方式可做进度条) while (!result.IsCompleted) { Thread.Sleep(100); Console.WriteLine("请继续等待!"); } //方式三 method.EndInvoke(result); #endregion Console.WriteLine("*******end AsyncAdvanced********"); #region 接收返回值 Func <string, long> method_result = GetSomething; result = method_result.BeginInvoke(str, callback, "dsh"); //主线程得到返回值 long lResult = method_result.EndInvoke(result); #endregion Console.Read(); }
/// <summary> /// Wraps handler for Asynchronous execution /// </summary> /// <typeparam name="TEvent"></typeparam> /// <param name="handler"></param> /// <param name="eventBusService">eventBusService to use, EventBus.Default if null</param> /// <returns></returns> public static Delegate <TEvent> Async <TEvent>(this Delegate <TEvent> handler, EventBusService eventBusService = null) { return((param) => { handler.BeginInvoke(param, new AsyncCallback <TEvent>(handler, eventBusService == null ? EventBus.Default : eventBusService) .Callback, null); }); }
/// <summary> /// 异步方法 /// </summary> public static void Async() { Console.WriteLine("*******Async********"); for (int i = 0; i < 5; i++) { string str = string.Format("Async-{0}", i); Delegate dele = DoSomething; dele.BeginInvoke(str, null, null); } Console.WriteLine("*******end Async********"); Console.Read(); }
public void ShowAndCalculate(string query, string appkey) { this.Show(); Properties.Settings.Default.WA_RespSend++; Properties.Settings.Default.Save(); Engine = new WolframAlphaEngine(appkey);//KLQJ9W-5UU8EGQUG3 WolframAlphaQuery WAQ = new WolframAlphaQuery(); WAQ.APIKey = appkey; WAQ.MoreOutput = false; WAQ.Asynchronous = false; WAQ.AllowCaching = false; WAQ.Query = query; WAQ.TimeLimit = 30000; WAQ.Format = WolframAlphaQueryFormat.PlainText + "," + WolframAlphaQueryFormat.Image; pictureLoadAnim.Image = Properties.Resources.anim_0; loadingslide = 0; timerAnim.Start(); del = new Delegate(Engine.LoadResponse); del.BeginInvoke(WAQ, new AsyncCallback(CallBackFunc), null); }