Why I get an exception: "InvalidOperationException: Cross-thread operation not valid: Control lblText
accessed from a thread other than the thread it was created on" :when running application in debug mode?:
namespace testFormApp
{
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void Form1_Load(object sender, EventArgs e)
{
lblText.Click += (send, arg) => Need = false;
}
bool Need = true;
private async void ButtonStart_Click(object sender, EventArgs e)
{
await Task.Run(async() =>
{
lblText.Text = "";
while(Need)
{
lblText.Text += ". ";
await Task.Delay(1000);
}
});
}
}
}
But same code in Release mode working without any problem. Why I'm getting this exception?
Checkout Hans Passant's answer on this question, Why is cross thread operation exception not thrown while running exe in bin\Debug he is saying cross-thread error checking is only enabled when a debugger is attached, also you can disable cross-thread errors check manually
Control.CheckForIllegalCrossThreadCalls = false;