williamg
williamg

Reputation: 2758

C# - When to Make Thread-Safe Calls

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.

Upvotes: 0

Views: 177

Answers (2)

Guffa
Guffa

Reputation: 700680

You only need to invoke the code when the code is not running in the GUI thread.

I can't control which piece of code is executed by which thread

Yes, you can. There is nothing unpredictable about which code runs in the GUI thread, you just have to find out what the rules are.

The only code to run out of the GUI thread in your code would be methods that runs as an asynchronous callback, for example a timer or an asynchronous web request. (The System.Windows.Forms.Timer runs the Tick event in the GUI thread though.)

(There are other ways of running code in another thread, but then you would be aware of using multi-threading.)

Upvotes: 0

Femaref
Femaref

Reputation: 61477

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.

Upvotes: 1

Related Questions