C# Winform 窗體界面”假死”后台線程阻塞 解決辦法–BeginInvoke


這個方法可以用在任何后台任務耗時較長,造成界面“假死”界面控件不更新的情況。
比如要要執行的數據庫操作是幾十萬條的update語句,如果在click事件里阻塞或者做Thread.Sleep或一個耗時很長的操作,窗口就會無響應點不動了。故需要用this.BeginInvoke方法來異步執行UI線程的操作,更新界面顯示。

 

//導入按鈕點擊事件

private void btn_import_Click(object sender,EventArgs e)

{

    //1.綁定需要執行的操作方法

    var act = new Action(Import);

    act.BeginInvoke(ar => act.EndInvoke(ar), null);  //參數null可以作為回調函數的返回參數

}

 

//回調函數(此處為無返回值函數,也可自行改寫)

private void Import()

{

    this.btn_import.Enable = false;

    this.btn_import.Text = "正在導入...";

    DateTime starttime = System.DateTime.now;

    try

    {

        //2.執行導入數據庫操作

        //如:sqlhelper.ExecuteNonQuerySqlByTransation(sqlstr);

 

        //3.執行異步操作

        this.BeginInvoke(new Action(() =>

        {

            DateTime endtime = System.DateTime.now;

            TimeSpan = ts = endtime.Subtract(starttime);

            this.txt_result.Text = "導入了 " + successcount + " 條記錄。";

            this.lb_time.Text = "一共消耗了 " + (int)ts.TotalMinutes + " 分鍾, " + ts.Seconds + " 秒。";

            this.btn_import.Enable = true;

            this.btn_import.Text = "點擊開始導入";

        }));

    }

    catch(Exception e)

    { }

原文鏈接: http://www.91w.net/codesnippet/339.html


免責聲明!

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



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