1

I have a MainForm and method which opens new window:

private void OpenWindow(object source, ElapsedEventArgs e)
{
    var form = new SomeForm();
    form.MdiParent = this;
    form.Show();
}

And timer:

System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OpenWindow);
timer.Interval = 10000;
timer.Enabled = true;

And it throws error on setting MdiParent: form.MdiParent = this;

Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on.

How can I solve this problem?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
godot
  • 3,422
  • 6
  • 25
  • 42
  • 2
    Try using another Timer. https://stackoverflow.com/questions/10317088/why-there-are-5-versions-of-timer-classes-in-net – user11909 Oct 19 '18 at 10:35
  • its an idea! thank you, I'll try – godot Oct 19 '18 at 10:41
  • Possible duplicate of [Writing to a TextBox from another thread?](https://stackoverflow.com/questions/519233/writing-to-a-textbox-from-another-thread) – rs232 Oct 19 '18 at 10:56
  • 1
    @user2190035 your idea helped me, if you write it as detailed answer, I'll accept it. P.S thanks – godot Oct 19 '18 at 11:00

2 Answers2

1

You could use one of the other Timers because they handle the threading differently.

Explained here: Why there are 5 Versions of Timer Classes in .NET?

user11909
  • 1,235
  • 11
  • 27
0

Based on Threading Model article, I think this should works in your cas:

var form = new SomeForm();
if (form.InvokeRequired)
{
    form.Invoke(new MethodInvoker(delegate {
    form.MdiParent = this;
    }));
}
form.Show();

Or like this:

Invoke(new Action(() =>
{
    form.MdiParent = this;
    form.Show();
}));
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • thank you for answer, but in this form I use xtraTabControl and I'm getting following error: "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it." – godot Oct 19 '18 at 10:50
  • @godot Have a look at my updated answer. it is another approach. – Salah Akbari Oct 19 '18 at 10:54
  • @godot Or you might need to add the `[STAThread]` attribute on your method. – Salah Akbari Oct 19 '18 at 10:59
  • thanks for answer again, +1 from me. Got another solution, just used another timer – godot Oct 19 '18 at 11:53