c#界面卡死处理方法

方法一:

设置属性:

Control.CheckForIllegalCrossThreadCalls = false;

开启一个新线程

Thread th = new Thread(() => Search(detailID.Trim()));
th.IsBackground = true;
 th.Start();
 public void Search(string detailID)
{
dataGridView1.DataSource =BLLBillConsume.BllGetClearMarketLog_detail(detailID);
dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;//文本向右对齐
 }

 

上面的方法不推荐,推荐以下方法:

拖一个组件backgroundWorker

设置属性:

backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;

执行用时较长的操作,

backgroundWorker1.CancellationPending是用来判断是否允许用户取消
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            dtMain = BLLBillConsume.BllGetClearMarketLog_detail(detailID);
            if (!backgroundWorker1.CancellationPending)
            {//退出
                backgroundWorker1.CancelAsync();
            }
        }
Thread.Sleep(100000);只是为了模拟界面卡死

然后就显示查询到的数据
 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            dataGridView1.DataSource = dtMain;
            dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;//文本向右对齐
            //Search(detailID.Trim());
        }

这个是开启线程

  backgroundWorker1.RunWorkerAsync();

 

 

 

posted @ 2017-09-02 19:50  沉迷编程的程序员  阅读(1061)  评论(0编辑  收藏  举报