WinForm查詢大數據界面假死,使用異步調用解決


用DataGridView無分頁綁定一個幾千條數據的查詢,查詢的時候界面直接卡死十幾秒,用戶體驗非常不好,因此用異步操作解決界面卡死的問題
原本場景:點擊[查詢]后,界面直接卡死
優化場景:點擊[查詢]后,界面可以隨意移動,感覺不到后台在做大量數據的讀取和綁定

private void btnQuery_Click(object sender, EventArgs e)
{
    // 查詢按鈕點擊后,按鈕文本由"查詢"改為"加載中",並把按鈕狀態改為不可點擊
    btnQuery.Text = "加載中...";
    btnQuery.Enabled = false;
    // 使用匿名方法定義一個委托事件,委托事件主要操作數據庫查詢,並返回查詢的結果,不涉及任何UI操作    
    Func<DataTable> act = () =>
    {
        string sqlstmt = GetQuerySQL();
        DbParams dbpara = new DbParams(DbFactory.Instance.ProviderName);
        dbpara.AddInputDateTime("@beginTime", dtpStart.Value);
        dbpara.AddInputDateTime("@endTime", dtpEnd.Value);
        DataTable dtUserList = DbFactory.Instance.ExecuteDataTable(sqlstmt, dbpara.ToArray());
        return dtUserList;
    };
    // 異步調用委托事件,在委托事件回調方法中,使用任意控件的異步方法把查詢結果綁定到數據表控件中
    act.BeginInvoke((result) =>
    {
        DataTable dtResult = act.EndInvoke(result);
        // this是當前WinForm窗口的實例,也可以替換為界面中的任意控件示例,如dgvMain.BeginInvoke
        this.BeginInvoke(new Action<DataTable>((DataTable dtList) =>
        {
            dgvMain.DataSource = dtList;
            btnQuery.Text = "查詢(&Q)";
            btnQuery.Enabled = true;
        }), dtResult);
    }, null);
}

WinForm DataGridView顯示行頭序號代碼

this.dgvMain.RowPostPaint += (object sender, DataGridViewRowPostPaintEventArgs e) =>
{
    DataGridView dgv = sender as DataGridView;
    SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
    e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dgv.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 7);
};

 

參考文章:
http://www.cnblogs.com/yuyijq/archive/2010/01/11/1643802.html

 

版權聲明:本文采用署名-非商業性使用-相同方式共享(CC BY-NC-SA 3.0 CN)國際許可協議進行許可,轉載請注明作者及出處。
本文標題:WinForm查詢大數據界面假死,使用異步調用解決
本文鏈接:http://www.cnblogs.com/sochishun/p/7168815.html
本文作者:SoChishun (郵箱:14507247#qq.com | 博客:http://www.cnblogs.com/sochishun/)
發表日期:2017年7月14日


免責聲明!

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



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