I have a large project that I’m working on in C#, a language I’m fairly new to. The project heavily relies on a GUI and there is a lot of data that is displayed. Recently, we’ve been getting cross-threading errors in places that they never were before. These errors where they occurred were easily solved:
if (logListView.InvokeRequired)
{
logListView.BeginInvoke(new MethodInvoker(
() => logListView.Items[logListView.Items.Count - 1].EnsureVisible()));
}
else
{
logListView.Items[logListView.Items.Count - 1].EnsureVisible();
}
My question however, is this: Does that method need to be applied EVERY TIME I access a Windows Form object? Are there special cases? I’m not using multi-threading, so to the best of my knowledge where these errors occur are out of my control. E.g. I can’t control which piece of code is executed by which thread: C# is doing all of that on it’s own (something I don’t really understand about the language). Implementing an if statement for each line that modifies the GUI seems exceptionally obnoxious.
You only need that code if you access winform components from outside the UI thread (ie. from any thread you have spawned). There are some components in the core library that spawn threads, for example the
FileSystemWatcher. Winforms doesn’t just spawn threads on its own, it only has the UI thread. Any cross-thread issues occur because of code you wrote or libraries you use.