I have the following Windows Forms code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(SampleFunction).Start();
}
void SampleFunction()
{
for (int i = 0; i < 10; i++)
{
if (textBox1.InvokeRequired == true)
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text += "HI. "; });
else
textBox1.Text += "HII. "; // Sometimes hit on first pass of the loop.
Thread.Sleep(1000);
}
}
When debugging the above code using breakpoints, I am observing that the non-invoke-required path is hit on a first pass, but only once about every 10 runs. I am surprised because the code is on a separate thread, and I am expecting InvokeRequired
to be true at all times. Can someone please shed light?