Share via

Problem with autosave function?

Ken Ekholm 236 Reputation points
2021-06-08T11:06:29.327+00:00

I get the following error with this code below this text.
Message=Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
Can someone help me?

 private void OnTimeEvent(object sender, System.Timers.ElapsedEventArgs e) 
            {
                if (saved == true)
                {
                    saved = false;
                    richTextBoxInfo.Invoke((MethodInvoker)(() => richTextBoxInfo.Text = richTextBoxInfo.Text));
                    File.WriteAllText(@"wininfo.txt", richTextBoxInfo.Text);
                    timerSave.Stop();
                    MessageBox.Show("Saved!");
                }
            }
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2021-06-08T12:21:16.667+00:00

    Try changing two lines:

    string text = null;
    richTextBoxInfo.Invoke((MethodInvoker)(() => text = richTextBoxInfo.Text));
    File.WriteAllText(@"wininfo.txt", text);
    

    Also check if the saved variable is used correctly.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.