简体   繁体   中英

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. Eg 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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM