.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

  • Mastering Blazor Authentication and Authorization

    At the Visual Studio Live! @ Microsoft HQ developer conference set for August, Rockford Lhotka will explain the ins and outs of authentication across Blazor Server, WebAssembly, and .NET MAUI Hybrid apps, and show how to use identity and claims to customize application behavior through fine-grained authorization.

  • Linear Support Vector Regression from Scratch Using C# with Evolutionary Training

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the linear support vector regression (linear SVR) technique, where the goal is to predict a single numeric value. A linear SVR model uses an unusual error/loss function and cannot be trained using standard simple techniques, and so evolutionary optimization training is used.

  • Low-Code Report Says AI Will Enhance, Not Replace DIY Dev Tools

    Along with replacing software developers and possibly killing humanity, advanced AI is seen by many as a death knell for the do-it-yourself, low-code/no-code tooling industry, but a new report belies that notion.

  • Vibe Coding with Latest Visual Studio Preview

    Microsoft's latest Visual Studio preview facilitates "vibe coding," where developers mainly use GitHub Copilot AI to do all the programming in accordance with spoken or typed instructions.

  • Steve Sanderson Previews AI App Dev: Small Models, Agents and a Blazor Voice Assistant

    Blazor creator Steve Sanderson presented a keynote at the recent NDC London 2025 conference where he previewed the future of .NET application development with smaller AI models and autonomous agents, along with showcasing a new Blazor voice assistant project demonstrating cutting-edge functionality.

Subscribe on YouTube