It is generally a bad idea to access your UI from a different thread than the one which started the UI. It is possible to avoid the exception by setting the static property Control.CheckForIllegalCrossThreadCalls
to false
, but that is a very dangerous way.
You should rather use Control.BeginInvoke
to defer execution back to the UI thread.
So you could replace your line txtSql.Text = sQuery
to something like that:
void RunChecks()
{
...
SetQueryText(sQuery); // instead of txtSql.Text = sQuery;
...
}
delegate void SetTextDelegate(string text);
void SetQueryText(string query)
{
if (txtSql.InvokeRequired)
{
txtSql.BeginInvoke(new SetTextDelegate(SetQueryText), query);
return;
}
txtSql.Text = query;
}
So SetQueryText
checks if it is necessary to call Invoke
(or BeginInvoke
) because it was called from another thread. If this is the case, it calls BeginInvoke
to defer execution to the UI thread and returns.
Unfortunatly this still uses the delegate syntax instead of lambdas, but maybe there's a better syntax that I just don't know.
You need to do this for all controls you are accessing from different threads.