c# Thread issue using Invoke from a background thread

前端 未结 5 711
故里飘歌
故里飘歌 2020-12-11 20:07

I\'ve got thread, which processes some analytic work.

   private static void ThreadProc(object obj)
    {
        var grid = (DataGridView)obj;
        forea         


        
5条回答
  •  轮回少年
    2020-12-11 20:44

    You have a deadlock. Your t.Join is blocking the GUI thread until ThreadProc is done. ThreadProc is blocked waiting for t.Join to finish so it can do the Invokes.

    Bad Code

        Thread t = new Thread(new ParameterizedThreadStart(ThreadProc)); 
        t.Start(dgvSource); 
        t.Join();  <--- DEADLOCK YOUR PROGRAM
        MessageBox.Show("Done", "Info"); 
    

    Good Code

       backgroundWorker1.RunWorkerAsync
    
      private void backgroundWorker1_DoWork(object sender, 
            DoWorkEventArgs e)
        {    
            var grid = (DataGridView)obj;    
            foreach (DataGridViewRow row in grid.Rows)    
            {    
                if (Parser.GetPreparationByClientNameForSynonims(row.Cells["Prep"].Value.ToString()) != null)    
                    UpdateGridSafe(grid,row.Index,1);    
                // don't need this Thread.Sleep(10);    
            }    
        }  
    
       private void backgroundWorker1_RunWorkerCompleted(
                object sender, RunWorkerCompletedEventArgs e)
            {
            MessageBox.Show("Done", "Info"); 
    }
    

    EDIT

    Also use BeginInvoke instead of Invoke. That way your worker thread doesn't have to block every time you update the GUI.

    Reference

    Avoid Invoke(), prefer BeginInvoke()

提交回复
热议问题