WPF 异步执行

 

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值