1

I am seeing the following error in Visual Studio within a class called CreateAlarm.cs tied to a user control.

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

This code is called on the following method:

private void ClearPanel()
{
    panel1.Controls.Clear();
}

The way the program operates is that this line of code is the method that clears a panel of user controls, before more user controls are added by calling the method on the main form from within a user control.

The code that calls this method that is causing problems (when the error is caused) is the following:

void CreateAlarm_TimeElapsed()
{
    ClearPanel();
    Alarm alarmScreen = new Alarm(); // this creates an instance of the user control
    AddToPanel(alarmScreen);
}

Where this code is actually called from within a user control with events and delegates.

The problem is otherwise identical code for a separate page is causing problems. I am thinking it could be because the code is run by a timer ending using System.Timers.

Does anyone have any ideas as to what could be the problem? Or additional information about the potential causes of the error message?

Thanks :)

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
TimDuncan
  • 11
  • 1
  • Hi. Is this WPF or Winforms? – Marlonchosky May 11 '20 at 22:37
  • why don't use in timer if its in current page, what I understand form you question is this happen when you are in other page? – Ari May 11 '20 at 22:48
  • 3
    I think, that you are right. The problem is likely caused by using *System.Timers.Timer*, because it by default executes handlers of the *Elapsed* event in the *ThreadPool*. To fix the problem you should either set [*SynchronizingObject*](https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.synchronizingobject?view=netcore-3.1) property of the *Timer* or use *System.Windows.Forms.Timer*. – Iliar Turdushev May 11 '20 at 22:53

0 Answers0