How to limit only one thread for network operation for update cached data

1 minute read ~

Managing concurrent network operations is crucial when updating cached data to avoid race conditions and unnecessary load. In .NET, you can achieve this using the Interlocked.Exchange method.

How It Works

Interlocked.Exchange sets a variable to a specified value and returns its original value as an atomic operation. This is useful for synchronizing access between multiple threads.

Consider the following condition:

if (Interlocked.Exchange(ref _networkOperationsInProgress, 1) == 0)

This checks if _networkOperationsInProgress changes from 0 to 1. If true, it means no network operation is running, and the current thread can proceed. If another operation is already in progress, the value remains 1, so the condition is false and the code block does not execute.

After the network operation completes, set the value back to 0 to allow future operations:

Interlocked.Exchange(ref _networkOperationsInProgress, 0);

This pattern is useful for scenarios like reading and updating a Redis cache with a lock before the value expires.

Example Code

public class ValueRefresher
{
    // To avoid concurrent network operations, this flag is used 
    // to achieve synchronization between multiple threads.
    private int _networkOperationsInProgress = 0;

    public async Task RefreshAsync()
    {
        if (Interlocked.Exchange(ref _networkOperationsInProgress, 1) == 0)
        {
            try 
            {
                //TODO: Refresh value here from network
            }
            finally
            {
                Interlocked.Exchange(
                    ref _networkOperationsInProgress, 
                    0);
            }
        }
    }
}

Reference

Microsoft Corporation. (2025). AzureAppConfigurationProvider.cs. In Azure/AppConfiguration-DotnetProvider (C# source code). GitHub.

Categories:

Updated:

Leave a Comment