Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 7 July 2025

Quick Look: Controlling Concurrency with SemaphoreSlim in C#

When building high-throughput or asynchronous applications in .NET, it is easy to overwhelm external resources—like hitting an external API rate limit or exhausting database connection pools—by running too many tasks at once.

While lock or Monitor limits access to a single thread at a time, C# provides SemaphoreSlim when you need to allow a controlled number of concurrent tasks to access a resource.


What Problem Does SemaphoreSlim Solve?

Imagine you have 1,000 items to process, and each item requires calling a third-party REST API. If you run them all concurrently using Task.WhenAll, you might fire 1,000 simultaneous HTTP requests, leading to:

  • HTTP 429 Too Many Requests or rate-limiting errors.
  • Socket exhaustion or high resource contention.
  • Database thread-pool starvation under heavy loads.

SemaphoreSlim acts as a gatekeeper with a fixed capacity. If you set its capacity to 3, it allows up to 3 tasks to run concurrently. A 4th task must wait in line until one of the first three completes and releases its slot.

Why SemaphoreSlim over Semaphore? 

SemaphoreSlim is a lightweight, non-OS-level sync primitive optimized for speed within a single process. Crucially, it supports WaitAsync(), making it fully non-blocking and ideal for modern async/await code.

 

The Code Example

Here is a practical pattern for throttling concurrent asynchronous operations:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class ApiBatchProcessor
{
    // Limit concurrency to a maximum of 3 tasks at any given time
    private static readonly SemaphoreSlim Throttler = new SemaphoreSlim(initialCount: 3, maxCount: 3);

    public async Task ProcessItemsAsync(IEnumerable<int> itemIds)
    {
        var tasks = itemIds.Select(id => ProcessSingleItemAsync(id));
        await Task.WhenAll(tasks);
    }

    private async Task<int> ProcessSingleItemAsync(int id)
    {
        // Asynchronously wait to enter the semaphore without blocking the thread
        await Throttler.WaitAsync();

        try
        {
            Console.WriteLine($"[Processing] Item {id} started on Thread {Environment.CurrentManagedThreadId}");
            
            // Simulate an expensive API call or database query
            await Task.Delay(1000); 

            return id;
        }
        finally
        {
            // ALWAYS release the semaphore in a finally block to prevent deadlocks
            Throttler.Release();
        }
    }
}

Key Takeaways & Best Practices

  1. Always Use try...finally for Release():
Always call Release() inside a finally block. If the task throws an unhandled exception before releasing the semaphore, that slot is lost forever, leading to an eventual application deadlock.

 

      2. Non-Blocking with WaitAsync():

Never call Wait() inside an async method—use await WaitAsync(). Wait() blocks the underlying thread pool thread while waiting, whereas WaitAsync() frees the thread to do other work until a slot opens up.

 

      3.  Configuring Limits: 

The constructor SemaphoreSlim(initialCount, maxCount) defines how many slots are initially available and the absolute maximum allowed limit. Typically, both values are set to the same number (e.g., new SemaphoreSlim(5, 5)).

Saturday, 5 July 2025

Quick Look: Clean In-Memory Caching Wrapper in .NET

Caching expensive operations—like database queries or external API calls—is one of the easiest ways to improve performance in .NET applications. While IMemoryCache from Microsoft.Extensions.Caching.Memory is easy to use out of the box, boilerplate setup often litters repository and service classes.

Here is a quick look at a simple, reusable CacheService wrapper that leverages C# primary constructors and attributes to make caching clean and declarative.

The Code

using System.Runtime.CompilerServices;
using Microsoft.Extensions.Caching.Memory;

namespace UWAuth.Services;

/// <summary>
/// Implements a service for caching data using <see cref="IMemoryCache"/>.
/// </summary>
public class CacheService(IMemoryCache cache)
{
    private const int CacheDuration = 5;

    /// <summary>
    /// Gets the cached data for the specified key or fetches it using the provided fetch task if not cached.
    /// </summary>
    /// <typeparam name="T">The type of the data to cache.</typeparam>
    /// <param name="fetchTask">The task to fetch the data if not cached.</param>
    /// <param name="customCacheDuration">The custom cache duration in minutes. Default is 5 minutes.</param>
    /// <param name="key">The cache key. Default is the caller member name.</param>
    /// <returns>The cached or fetched data.</returns>
    /// <exception cref="InvalidOperationException">Thrown if the cached data cannot be cast or deserialized.</exception>
    public async Task<T> GetOrFetch<T>(
        Func<Task<T>> fetchTask, 
        int customCacheDuration = CacheDuration, 
        [CallerMemberName] string key = "") 
        where T : class?
    {
        if (cache.TryGetValue(key, out var cached))
        {
            return cached as T ?? throw new InvalidOperationException($"Failed to deserialize cached items for {key}");
        }

        var items = await fetchTask();
        if (items is null)
        {
            return null!;
        }

        cache.Set(key, items, TimeSpan.FromMinutes(customCacheDuration));
        return items;
    }

    /// <summary>
    /// Invalidates the cached data for the specified key.
    /// </summary>
    /// <param name="key">The cache key.</param>
    /// <void>Invalidates the cache entry.</void>
    public void Invalidate(string key) => cache.Remove(key);
}

Key Highlights & Features

  1. Modern C# Primary Constructor Syntax: By defining public class CacheService(IMemoryCache cache), the IMemoryCache dependency is injected directly into the class header—eliminating private field declarations and boilerplate constructor assignments.

  2. Implicit Cache Keys via [CallerMemberName]: Instead of manually defining string keys like "GetUserProfile", the [CallerMemberName] attribute automatically captures the name of the calling method or property. If called inside GetUserInfo(), the key automatically becomes "GetUserInfo".

  3. Get-or-Fetch Pattern: The GetOrFetch<T> method handles the standard checking pattern:

    • Cache Hit: Checks TryGetValue. If found, safely casts and returns the cached object.

    • Cache Miss: Runs the fetchTask delegate, saves the result in IMemoryCache using TimeSpan.FromMinutes(), and returns the fresh data.

  4. Invalidation: Includes a clean Invalidate(string key) helper for manual cache purging when underlying data is updated or deleted.

How to Use It in Your Code

After registering IMemoryCache and CacheService in your DI container (builder.Services.AddMemoryCache()), you can inject CacheService anywhere:

public class UserService(CacheService cacheService, IUserDbContext dbContext)
{
    public async Task<List<User>?> GetActiveUsers()
    {
        // Cache key automatically defaults to "GetActiveUsers" via [CallerMemberName]
        return await cacheService.GetOrFetch(async () => 
        {
            return await dbContext.Users.Where(u => u.IsActive).ToListAsync();
        }, customCacheDuration: 10);
    }

    public void PurgeActiveUserCache()
    {
        cacheService.Invalidate(nameof(GetActiveUsers));
    }
}

Sunday, 1 September 2019

Working with AWS Parameter Store in .NET

Using from code

Before starting, I installed the AWS CLI. When trying to figure out how to pass credentials into the AWS SDK, I stumbled upon the SDK's local credential discovery chain.

Among other options, the SDK automatically checks for local configuration files created in your user directory when you run aws configure via the CLI. It handles authentication seamlessly behind the scenes—a handy trick for local development!

Setting Up the Project & Package

I created a new ASP.NET Core MVC project and added the official AWS configuration package via NuGet:


Then I created a simple “Settings” class that holds the configuration values we’ll get back from AWS.
public class Settings
{
   public string awsvalue { get; set; }
   public string awsvalue2 { get; set; }
}
In the appsettings.json file, I told my app which AWS region to use.
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AWS": {
    "Profile": "default",
    "Region": "us-west-2"
  }
}
In Program.cs, I updated the web host builder to hook into Systems Manager as a configuration provider. Here, I'm pulling all settings stored under the /seroterdemo path:
public class Program
{
  public static void Main(string[] args)
  {
     CreateWebHostBuilder(args).Build().Run();
  }

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
       .ConfigureAppConfiguration(builder =>
       {
          builder.AddSystemsManager("/seroterdemo");
       })
       .UseStartup<Startup>();
    }

Binding and Accessing Options

To make these values available to the application, I bound the configuration section to my Settings POCO in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Settings>(Configuration.GetSection("properties"));

    services.Configure<CookiePolicyOptions>(options =>
    {
       options.CheckConsentNeeded = context => true;
       options.MinimumSameSitePolicy = SameSiteMode.None;
     });
}
Finally, I injected IOptionsSnapshot<Settings> into the controller constructor. Using IOptionsSnapshot ensures that when the background reload timer fetches updated parameters from AWS, the controller automatically picks up the latest values on the next request!
        private readonly Settings _settings;

        public HomeController(IOptions<Settings> settings)
        {
            _settings = settings.Value;
        }

        public IActionResult Index()
        {
            ViewData["configval"] = _settings.awsvalue;
            ViewData["configval2"] = _settings.awsvalue2;

            return View();
        }
After updating my View to render the two properties, I launched the application—and both values stored in Parameter Store populated as expected.

What I Like About Parameter Store

  • Unbeatable Price: Standard parameters are free (up to 10,000 per account), which makes it a no-brainer for basic configuration and string parameters.

  • Full Audit Trail: Every update increments the version number and records an explicit change history showing who changed what and when.

  • Native .NET Core Integration: AWS’s Amazon.Extensions.Configuration.SystemsManager package integrates seamlessly into ASP.NET Core’s native IConfigurationBuilder, complete with automatic background reloads using TimeSpan.

The AWS team built this extension for .NET Core, and they added capabilities for reloading parameters automatically. Nice touch!

Thursday, 8 January 2015

Improving ASP.NET MVC Performance with Output Caching

You can dramatically improve the performance of your ASP.NET MVC application by taking advantage of the framework's built-in output caching mechanism. If you have a high-traffic page or an action that queries a large dataset from the database, output caching allows you to cache the HTML or JSON response directly in memory. By serving cached content for subsequent requests, you eliminate unnecessary database hits and drastically lower page load times.

In ASP.NET MVC 4 and 5, output caching can be implemented quickly using the standard [OutputCache] attribute without needing to build custom cache providers. Decorating your controller actions with this attribute gives you granular control over cache duration, location, and invalidation rules.

Default Caching Behavior in ASP.NET MVC

By default, GET actions in ASP.NET MVC return a Cache-Control header set to private. Consider a standard AJAX endpoint returning JSON:


public JsonResult Details(int id)
{
    // Fetch data for the specified ID
    var result = _repository.GetDetails(id);

    return Json(result, JsonRequestBehavior.AllowGet);
}

If you inspect the response headers using Fiddler or Browser Developer Tools, you will see output similar to this:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 4.0

Because Cache-Control is set to private, browsers (especially Internet Explorer) might cache these AJAX responses locally for the current user session. This can lead to stale data or unexpected application behavior when underlying data changes. Explicitly configuring output caching gives you predictability and control over client and server cache rules.

Enabling the [OutputCache] Attribute

To control caching explicitly, decorate your action method with the [OutputCache] attribute and specify a Duration (in seconds):


[OutputCache(Duration = 6)]


public ActionResult Search(string searchText)
{


return Json(SearchWebService.MyWebServiceInstance.AutocompleteSearchClient(searchText),JsonRequestBehavior.AllowGet);

}

Inspecting the HTTP response headers now reveals updated cache directives:

HTTP/1.1 200 OK
Cache-Control: public, no-transform, max-age=60
Expires: Mon, 29 Oct 2015 09:18:37 GMT
Last-Modified: Mon, 29 Oct 2015 09:17:37 GMT
Content-Type: application/json; charset=utf-8

Testing It in Visual Studio

  1. Remove the [OutputCache] attribute and place a breakpoint inside your action method.

  2. Launch your application and press F5 (Refresh) in your browser—the breakpoint hits on every request.

  3. Add [OutputCache(Duration = 60)] back to the action and refresh again.

  4. The breakpoint hits once for the initial request. Subsequent refreshes within the 60-second window serve cached content instantly without stepping into the controller action.

Handling Dynamic Content with VaryByParam

When an action returns different content based on query strings or route parameters, you must instruct the cache engine to store separate instances for each variation using VaryByParam.

  • VaryByParam = "none": Ignores all incoming parameters and serves the exact same cached payload to every user.

  • VaryByParam = "*": Creates a unique cache entry for every unique combination of query parameters.

  • Explicit Parameter List: Specify exact parameters separated by semicolons (e.g., VaryByParam = "accountId;page").

For example, when caching a paginated or sorted grid:


[OutputCache(Duration = 1, VaryByParam = "*")]
public ActionResult Index(int accountId, string page, string sort, string sortdir)
{

///code to get all accounts



return PartialView("_AccountsList", data);

}

Using VaryByParam = "*" guarantees that requests for ?accountId=1&page=2 and ?accountId=1&page=3 receive their corresponding cached views rather than returning the same cached data for both pages.