I have a multi threaded app and based on a propertychange i wanted to do some actions, so i created an event handler for that and changed the property from a thread, but still when the event fires, and i try to access form elements in the event handler method visual studio complains that cross thread access is done. I dont understand why it is being considered as cross thread. This is my code,
public delegate void AppStateChangedEventHandler(int st);
public event AppStateChangedEventHandler AppStateChanged;
private int appState;
public int AppState
{
get { return this.appState; }
set
{
this.appState = value;
if (this.AppStateChanged != null)
{
this.AppStateChanged(value);
}
}
}
public void MainForm_AppStateChanged(int val)
{
if (val == 1)
{
totDwn.Text = "00:00:00";
totAct.Text = "00:00:00";
}
else if (val == 0)
{
tt.Reset();
sw.Reset();
}
}
Inside initializecomponent method i added
this.AppStateChanged += new AppStateChangedEventHandler(this.MainForm_AppStateChanged);
From inside the thread i changed the appstate property as
this.AppState = 1;
Now there are two problems
1)The first and important is vs complains that cross thread operation is being performed even though i am accessing GUI elements from the event handler.(i know how to handle this using invoke required and a delegate but i just need to know why it is like this)
2)VS keeps warning that AppStateChanged event is not part of Windows.form.
The first problem is whats really irritating me? Any ideas on this.
Edit: D’oh, I misread your question. You want to know why VS complains? It was a design decision by the C# language team to avoid the multitude of problems that cross-thread access to form controls has.
Technically there’s no reason to disallow this, but it’s better to break in a consistent and easily fixable way than to fail in weird ways seemingly at random due to two threads manipulating a non-threadsafe control.
The event is executed on the thread that fires it (your other thread), not on the one that registers it (the main/GUI thread).
To solve this problem, you have to make sure the event code is invoked on the correct thread to allow accessing GUI elements, which can be done like this: