private void Operate_OnClick(object sender, RoutedEventArgs e) { AsyncFindBox(); RadWindow.Alert("測試測試!"); } private void AsyncFindBox() { #region 需要將返回結果返回到UI上。 //異步任務封裝在一個delegate中, 此delegate將運行在后台線程 Func<string> asyncAction = this.AsyncActionMethod; //在UI線程中得到異步任務的返回值,並更新UI //必須在UI線程中執行 Action<IAsyncResult> resultHandler = delegate(IAsyncResult asyncResult) { //異步執行后,將值更新到UI上。 //string result= asyncAction.EndInvoke(asyncResult); //SearchValue.Text=result; }; //異步任務執行完畢后的callback, 此callback運行在后台線程上. //此callback會異步調用resultHandler來處理異步任務的返回值. AsyncCallback asyncActionCallback = delegate(IAsyncResult asyncResult) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, resultHandler, asyncResult); }; //在UI線程中開始異步任務, //asyncAction(后台線程), asyncActionCallback(后台線程)和resultHandler(UI線程) //將被依次執行 asyncAction.BeginInvoke(asyncActionCallback, null); #endregion #region 不需要將返回結果返回到UI上的。 //Func<string> asyncAction = this.AsyncActionMethod; //asyncAction.BeginInvoke(null, null); //Action asyncAction = this.FindBox; //方法無返回值 //asyncAction.BeginInvoke(null, null); #endregion } private string AsyncActionMethod() { var commandMessage = ""; Thread.Sleep(5000); Console.WriteLine(1111); // 發射亮燈 BasketLight.SendCmd(5, BasketLight.CmdType.Ready, 0, ref commandMessage); return ""; } private void FindBox() { var commandMessage = ""; Thread.Sleep(5000); Console.WriteLine(1111); // 發射亮燈 BasketLight.SendCmd(5, BasketLight.CmdType.Ready, 0, ref commandMessage); }