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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM