.NET Tips and Tricks

Blog archive

Protecting Shared Fields in Asynchronous Processing

Sometimes, in a C# application with multiple threads running simultaneously, you need to share data. So you set up a variable declared outside of any method or property (a "field") and have the different threads share data by updating and reading that variable. It should work ... but it doesn't and you can't figure out why.

The odds are that there's some bug in your asynchronous code that's creating the problem. However (and this is a long shot), it might be the compiler's fault. Some of the optimizations the compiler applies to a field assume that the field will only be accessed by a single thread at a time. This means your source code might look fine ... but the optimized code you're executing is doing something different.

There are two solutions in C#: First, put a lock around any code that accesses the field (this option is also available in Visual Basic). You might take a hit on performance as threads queue up to get to your field, but it ensures that you both keep the compiler's optimizations and have only one thread accessing the field at a time.

If you don't think you can find all the places that the field is being read or written (or are too lazy to look) you can, in C#, mark the variable as volatile:

internal volatile string Status;

The volatile keyword causes the compiler to omit the optimizations that assume single-thread access. You'll still take a performance hit because, internally, the compiler will cause reads and writes to your variable to be processed in sequence. But, now, when your application still doesn't work, you'll know it's your fault.

Visual Basic doesn't have an equivalent to the volatile keyword. However, if you can track down all the places where you read or write the field, you can use the Thread object's VolatileRead and VolatileWrite methods when working with the field.

Posted by Peter Vogel on 11/04/2015


comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events