0

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
zeroG
  • 320
  • 2
  • 12
  • apart from the reason(i strongly doubt release mode not reproducible) and fix, above code is badly designed. can you tell us the idea behind the code? – Lei Yang Jul 15 '21 at 14:46
  • iam trying to learn topic: ways to cancel task | now with boolean variable, after this i will check cancellationtoken – zeroG Jul 15 '21 at 14:47
  • 1
    Does this answer your question? [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – Sinatr Jul 15 '21 at 14:48
  • `Task.Run` will run your code on a thread pool thread which must not access UI elements. Just remove the `await Task.Run(async() =>`. – Klaus Gütter Jul 15 '21 at 14:57
  • he have problem with code, but i have not problem with code. Code working normal in Release mode but in Debug mode i getting that error. Outside visual studio, if i go to folder of app and open my app, he will work normal cuz code not have problem. My english is bad sorry, idk how to explain my problem good. – zeroG Jul 15 '21 at 15:00

1 Answers1

2

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;

Kliment Nechaev
  • 480
  • 1
  • 6
  • 13