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); }