c# Thread issue using Invoke from a background thread

前端 未结 5 723
故里飘歌
故里飘歌 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:22

    It's because you're joining on your worker thread. Your UI thread starts the background thread, then calls Join on it. This stops the UI thread from performing any other actions.

    During this, the background thread is doing its work and calling Invoke, which waits for the UI thread to respond. Because the UI thread is waiting for a Join, it won't ever process the request to invoke. Hence, deadlock.

    What you should do, is eliminate the Join and the MessageBox. Put the MessageBox into its own function.

    void NotifyDone() {
        if( InvokeRequired ) BeginInvoke( (MethodInvoker) NotifyDone );
        else {
            // Perform any post-processing work
            MessageBox.Show("Done", "Info");  
        }
    }
    

    When the background thread is done, simply call this method (and eliminate static from ThreadProc).

    private void ThreadProc(object obj)  
        {  
            var grid = (DataGridView)obj;  
            foreach (DataGridViewRow row in grid.Rows)  
            {  
                if (Parser.GetPreparationByClientNameForSynonims(row.Cells["Prep"].Value.ToString()) != null)  
                    UpdateGridSafe(grid,row.Index,1);  
                Thread.Sleep(10);  
            }  
            NotifyDone();
        }  
    

    And like everyone else has already said, the use of Sleep, especially at such a low interval is either dangerous, misleading or worthless. I'm in the count it worthless camp.

提交回复
热议问题