When to use ConfigureAwait(true/false)

ConfigureAwait(false) is a C# feature used with async and await to control how the continuation of an async method is scheduled after an awaited operation completes.

Here’s a breakdown of when and why you might need to call ConfigureAwait(false):

Understanding Synchronization Context

  • What it is: A synchronization context (System.Threading.SynchronizationContext) represents a way to queue work (continuations) to a specific thread or threads.
    • UI Applications (WinForms, WPF, Xamarin, old ASP.NET on .NET Framework): These have a UI thread. Operations that update the UI must run on this specific UI thread. The synchronization context ensures that continuations after an await (if it wasn’t configured otherwise) are posted back to this UI thread.
    • ASP.NET Core: By default, ASP.NET Core does not have a synchronization context that behaves like the UI one. It uses a more efficient internal mechanism for managing requests.
    • Console Apps / Library Code (typically): Often have no special synchronization context, or they use the default thread pool context.
  • How await uses it: When you await a Task, by default (without ConfigureAwait(false)), the runtime captures the current SynchronizationContext (if one exists) and the current TaskScheduler. When the awaited task completes, it attempts to post the remainder of the async method (the continuation) back to that captured context or scheduler.

When You SHOULD GENERALLY Use ConfigureAwait(false)

  1. Library Code (Most Common and Important Case):
    • If you are writing a general-purpose library (e.g., a NuGet package, a shared business logic layer, a data access layer) that is not specific to any UI framework or ASP.NET Core.Reason: Your library code doesn’t know what kind of application will call it. If it’s called from an application with a restrictive synchronization context (like a UI app), and your library’s async methods always try to resume on that captured context, it can lead to:
      • Performance Issues: Unnecessary context switching back to the UI thread for non-UI work.Deadlocks: Especially if the calling code is blocking on the async method (e.g., using .Result or .Wait(), which is an anti-pattern but can happen). The UI thread might be blocked waiting for your library method to complete, while your library method is waiting to get back onto the UI thread to complete. This is a classic deadlock.
      Solution: Use ConfigureAwait(false) on all (or almost all) await calls within your library. This tells the runtime, “I don’t need to resume on the original context; any available thread pool thread is fine.”
// In a library
public async Task<string> GetDataAsync()
{
    // _httpClient is an HttpClient instance
    var response = await _httpClient.GetStringAsync("some_api_endpoint")
                                  .ConfigureAwait(false); // Don't need original context

    // Process the response (doesn't need original context)
    var processedData = Process(response); 

    await Task.Delay(100).ConfigureAwait(false); // Another example

    return processedData;
}
}

When You MIGHT NOT NEED ConfigureAwait(false) (or when ConfigureAwait(true) is implied/desired)

  1. Application-Level Code in UI Applications (e.g., event handlers, view models directly interacting with UI):
    • If the code after an await needs to interact directly with UI elements (e.g., update a label, change a button’s state).Reason: You want the continuation to run on the UI thread’s synchronization context. This is the default behavior, so explicitly using ConfigureAwait(true) is redundant but not harmful. Omitting ConfigureAwait achieves the same.
// In a UI event handler (e.g., WPF, WinForms)
private async void Button_Click(object sender, RoutedEventArgs e)
{
    MyButton.IsEnabled = false; // UI update
    var data = await _myService.FetchDataAsync(); // This service call might use ConfigureAwait(false) internally
    // The continuation here will be back on the UI thread by default
    MyLabel.Text = data; // UI update
    MyButton.IsEnabled = true; // UI update
}

  1. Application-Level Code in ASP.NET Core (e.g., Controllers, Razor Pages, Middleware):
    • Generally, not strictly needed: ASP.NET Core doesn’t have a SynchronizationContext that causes the same deadlock problems as UI frameworks or older ASP.NET. HttpContext and related services are accessible without needing to be on a specific “request thread” in the same way UI elements need the UI thread.
    • However, some developers still apply ConfigureAwait(false) out of habit or for consistency if their codebase also includes library projects where it is critical. It typically doesn’t hurt in ASP.NET Core and might offer a micro-optimization by avoiding an unnecessary check for a context.
    • If you do rely on HttpContext (e.g., HttpContext.User) after an await, ensure your understanding of its flow. In ASP.NET Core, HttpContext is generally available to continuations regardless of ConfigureAwait, but being explicit about context requirements is never a bad idea.
  2. Console Applications:
    • Usually, console applications don’t have a restrictive SynchronizationContext (they use the thread pool context). So, ConfigureAwait(false) is often not strictly necessary for preventing deadlocks.
    • However, if the console app uses libraries that might install a custom SynchronizationContext, or if you are writing code that might be reused in other contexts, using ConfigureAwait(false) can still be a good defensive measure.

Summary Table:

ContextRecommendation for ConfigureAwait(false)Reason
General-Purpose Library CodeStrongly Recommended (Use it)Prevent deadlocks, improve performance when called from context-sensitive environments (e.g., UI).
UI Application Code (Event Handlers, VMs)Generally Not Needed (Default is fine)You often need to return to the UI thread for UI updates.
ASP.NET Core Application CodeOptional / Good PracticeNo UI-like SynchronizationContext causing deadlocks. Can be a micro-optimization or for consistency.
Console Application CodeOptional / Good PracticeUsually no restrictive context, but good for reusability or if custom contexts are involved.

Export to Sheets

Key Takeaway:

The most critical place to use ConfigureAwait(false) is in library code to make it robust and performant regardless of the calling application’s environment. In application-level code, the necessity depends on whether you need to return to a specific context (like the UI thread).

As of current date (May 16, 2025), this guidance remains standard practice in the .NET ecosystem.

Convert Enum to List in C#

We can use LINQ for this;

public class EnumModel
{
    public int Value { get; set; }
    public string Name { get; set; }
}

public enum MyEnum
{
    Name1=1,
    Name2=2,
    Name3=3
}

public class Test
{
        List<EnumModel> enums = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => new EnumModel() { Value = (int)c, Name = c.ToString() }).ToList();

        // A list of Names only, does away with the need of EnumModel 
        List<string> MyNames = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => c.ToString()).ToList();

        // A list of Values only, does away with the need of EnumModel 
        List<int> myValues = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => (int)c).ToList();

        // A dictionnary of <string,int>
        Dictionary<string,int> myDic = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).ToDictionary(k => k.ToString(), v => (int)v);
}

Reference

https://stackoverflow.com/questions/1167361/how-do-i-convert-an-enum-to-a-list-in-c

Blazor WebAssembly and Antiforgery token

EditForm comes with built-in anti-forgery token support. Blazor automatically secures the EditForm instances, saving you the hassle of explicitly handling CSRF protection.

Blazor WebAssembly apps run entirely in the browser and do not have a server-side processing pipeline where you would typically configure a middleware such as app.UseAntiforgery(). If your Blazor WebAssembly app interacts with server-side APIs, you should manage anti-forgery at the API level. However, if you already use token-based authentication to secure communication, anti-forgery tokens are generally not necessary. Token-based authentication, by its nature, mitigates the risks associated with CSRF, making additional anti-forgery tokens redundant.

Reference

https://learn.microsoft.com/en-us/xandr/digital-platform-api/token-based-api-authentication

C# tip (Primary Constructor)

View this class;

public class Product
{
   public string Name {get; set;}
   public decimal Price {get; set;}

   public Product(string name, decimal price)
   {
       Name = name;
       Price = price;
   }
}

This can be re-written as;

public class Product(string name, decimal price)
{
   public string Name {get; set;} = name;
   public decimal Price {get; set;} = price;
}

Seems we can save some lines with this new pattern.

Using Razor, how do I render a Boolean to a JavaScript variable?

This is our C# model;

public class Foo
{
  public bool IsAllowed {get; set;} = false;
}

We would like to read this property in JS;

let isAllowed = '@Model.IsAllowed' === '@true';
if (isAllowed)
{
    console.log('Allowed reading..');
}
else
{
    console.log('Reading not allowed..');
}

Reference

https://stackoverflow.com/questions/14448604/using-razor-how-do-i-render-a-boolean-to-a-javascript-variable

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean