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