0

A background thread needs to update a label on the form. It generates an event. The event handler looks like this

    void ShowResults(object sender,EventArgs e)
    {
        ....
        SetText( results.ToString() );
    }
    delegate void SetTextCallback(string text);
    private void SetText(string text)
    {
         if (this.resultsLabel.InvokeRequired)
         {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
         }
         else
         {
             this.resultsLabel.Text = text;
         }
    }

The label is being updated very quickly and everything seems to be working. The problem is that when I close the form the UI locks up. If I comment out the statement

SetText( results.ToString() );

Then the form closes correctly. How do I get it to close down properly?

CarbonMan
  • 4,350
  • 12
  • 54
  • 75
  • I have since changed it to a label (didn't really need a textbox), and the problem is still there. – CarbonMan Nov 10 '16 at 12:13
  • 1
    Using Invoke() is dangerous, very apt to cause deadlock. Which you'll trigger by trying to ensure that the thread is terminated when the form closes. Your UI thread is waiting for the thread to end, the thread is waiting for the Invoke() call to complete. Pretty easy to see in the Debug > Windows > Threads debugger window, look at what your UI thread is doing. Using InvokeRequired is in itself a threading race bug waiting to happen. The only truly safe way to do this is by not closing your window until *after* you know that thread completed. http://stackoverflow.com/a/1732361/17034 – Hans Passant Nov 10 '16 at 13:22

0 Answers0