The problem is, as your error says, that you launched a thread with a specific function. In your case, when you launch a thread using OnTimedEvent
, this functions is running on a different scope from your main application:

That means: whatever you try to access from OnTimedEvent
related to your main program or viceversa, will fail, as it's not running on the same scope. What can you do? I use delegations.
At first, you need to know the Context
on which your main application is running. So, create a global variable for your main application:
private SynchronizationContext uiContext;
Then, when you launch your application catch the state of the context like this:
public MainWindow()
{
uiContext = SynchronizationContext.Current;
}
With this, you can know the real context of your application or different functions. So, if you want to know if your OnTimedEvent
is running on a different context and delegate it you will do this:
if (SynchronizationContext.Current != uiContext)
{
uiContext.Post(delegate { EnableMenuAndButtons(o, args); }, null);
}
else
{
// Do your normal stuff here
}
And with that, you should be able to use variables with your thread and vivecersa.
o and args are my passed variables. I'm using WPF, but you can use this example with regular Windows Forms (but you will have to use it's specific methods).
The library you will need is System.Threading
.
Clarification: For you, like this:
private void OnTimedEvent(object sender, EventArgs e)
{
if (SynchronizationContext.Current != uiContext)
{
uiContext.Post(delegate { EnableMenuAndButtons(sender, e); }, null);
}
else
{
// Do your normal stuff here
CheckStatus(); // this function will update my UI base of information will receive from serial port
}
}
}