Skip to content

C# 5 (2012): async/await and caller info attributes

  • What shipped in C# 5 and which platform it was paired with.
  • How async and await replaced callback-based asynchronous code, and the mistakes that still cause deadlocks and lost exceptions.
  • Which async restrictions are specific to C# 5 (no await in catch or finally, no async Main).
  • How CallerMemberName, CallerFilePath and CallerLineNumber remove string literals from logging and INotifyPropertyChanged code.
  • The breaking change to foreach variable capture, and why the for loop did not change.

C# 5 is a small, historical release with one very large idea: asynchronous methods. Every current C# compiler still accepts its rules through LangVersion 5.

Item Value
Released August 2012
Paired runtime .NET Framework 4.5
Minimum toolset Visual Studio/Build Tools 2012, or the compiler bundled with .NET Framework 4.5
Default for TFM None. Defaults by target framework came later; .NET Framework projects default to C# 7.3 today
LangVersion 5
Support today .NET Framework 4.5 support ended January 12, 2016. Current compilers still accept LangVersion 5
Previews in this release None

Microsoft’s version history describes C# 5 as “a focused version of the language” in which “nearly all of the effort” went into the async model.

Feature Weight Mainly for Deep dive
async and await Headline App and library code async/await
Caller info attributes Headline Logging, diagnostics, UI view models This page
foreach variable is fresh per iteration Behavior change All code that captures loop variables This page

Each complete sample is a console program for one invented app, OrdersPortal. Create a project with dotnet new console, replace Program.cs with the sample, and replace the property group in the .csproj with the one below. Without the last two lines a modern template doesn’t build under C# 5, because nullable annotations and generated global using directives are newer features.

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>5</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>

The samples were built this way with .NET SDK 10.0.115 and run on the .NET 10.0.15 runtime. The output is shown under each sample. C# 5 has no top-level statements, string interpolation or async Main, so the samples use a classic Main method. Samples that print decimals set the invariant culture first so the output is the same on every machine.

Before C# 5, non-blocking I/O meant callbacks. You used the Asynchronous Programming Model (BeginX/EndX pairs with IAsyncResult) or chained Task.ContinueWith calls. Both spread one logical operation across several methods or lambdas, and both made try/catch, loops and early returns awkward. Fragment, the shape of pre-C# 5 code:

// Fragment: .NET Framework 4 style continuation chain.
Task<decimal> totalTask = client.GetOrderTotalTask(42);
totalTask.ContinueWith(t =>
{
if (t.IsFaulted) { Log(t.Exception); return; }
ui.ShowTotal(t.Result);
}, TaskScheduler.FromCurrentSynchronizationContext());

The async modifier lets a method contain await expressions. At each await the compiler splits the method into a state machine: if the awaited task is not finished, the method returns to its caller, and the rest of the body runs as a continuation when the task completes. Exceptions thrown by the awaited operation are rethrown at the await, so ordinary try/catch works. By default the continuation resumes on the captured SynchronizationContext (the UI thread in a desktop app); ConfigureAwait(false) opts out.

OrdersPortal fetches three order totals concurrently and audits a rejected lookup.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
public class OrderApiClient
{
// Simulates network latency; a real client would await HttpClient here.
public async Task<decimal> GetOrderTotalAsync(int orderId, CancellationToken cancellationToken)
{
// Library-style code: it doesn't need the caller's context after the await.
await Task.Delay(200, cancellationToken).ConfigureAwait(false);
if (orderId <= 0)
{
throw new ArgumentOutOfRangeException("orderId", "Order IDs start at 1.");
}
return orderId * 10.5m;
}
}
public class Program
{
public static void Main()
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // same output on every machine
// C# 5 has no async Main (that arrived in C# 7.1), so block once at the entry point.
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
var client = new OrderApiClient();
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
{
var stopwatch = Stopwatch.StartNew();
// Start all three requests before awaiting any of them.
var tasks = new List<Task<decimal>>();
foreach (var id in new[] { 1, 2, 3 })
{
tasks.Add(client.GetOrderTotalAsync(id, cts.Token));
}
decimal[] totals = await Task.WhenAll(tasks);
Console.WriteLine("Totals: " + string.Join(", ", totals));
Console.WriteLine(stopwatch.ElapsedMilliseconds < 500 ? "Ran concurrently" : "Ran one after another");
// C# 5 does not allow await inside catch or finally (CS1985).
// Capture the exception, leave the block, then await.
ArgumentOutOfRangeException failure = null;
try
{
await client.GetOrderTotalAsync(0, cts.Token);
}
catch (ArgumentOutOfRangeException ex)
{
// The exception surfaces at the await, as if the call were synchronous.
failure = ex;
}
if (failure != null)
{
await AuditAsync("Rejected order lookup: " + failure.ParamName);
}
}
}
private static async Task AuditAsync(string message)
{
await Task.Delay(10);
Console.WriteLine("AUDIT " + message);
}
}

Output:

Totals: 10.5, 21.0, 31.5
Ran concurrently
AUDIT Rejected order lookup: orderId

The three requests overlap because each task is started before any is awaited. Awaiting each call inside the loop would take three times as long.

  • Blocking on async code. Calling .Result or .Wait() from a thread with a single-threaded synchronization context (WinForms, WPF or a classic ASP.NET request) can deadlock: the continuation needs that thread, and the thread is blocked waiting for the continuation. Block only at a true entry point, as the console Main above does.
  • ConfigureAwait(false) belongs in library code. Microsoft’s guidance is to use it on every await in reusable libraries unless the code needs the captured context; it protects callers that block and avoids a thread hop. In application code that touches UI state after the await, leave it out. In ASP.NET Core there is no SynchronizationContext by default, so it changes nothing there.
  • No await in catch or finally. C# 5 reports “CS1985: Cannot await in a catch clause”. Capture the exception, leave the block, then await, as the sample does. C# 6 removed the restriction.
  • async void. The caller can’t await it or catch its exceptions. Reserve it for event handlers, which must return void.
  • async does not mean “runs on another thread”. An async method runs synchronously until its first incomplete await. CPU-bound work still blocks unless you move it with Task.Run.

Don’t wrap synchronous, CPU-bound library methods in Task.Run just to make them look asynchronous; let the caller decide. Short, purely in-memory operations gain nothing from async and pay for the state machine.

Logging helpers and INotifyPropertyChanged implementations needed the caller’s name as a string. String literals drift out of date when a member is renamed, and walking the stack is slow and is affected by inlining and obfuscation.

Apply [CallerMemberName], [CallerFilePath] or [CallerLineNumber] to an optional parameter. When the caller omits the argument, the compiler writes the value as a literal into the caller’s IL at compile time. Nothing happens at run time, so obfuscation does not affect the result.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
public static class Log
{
public static void Info(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine(string.Format("{0}:{1} {2} - {3}",
Path.GetFileName(filePath), lineNumber, memberName, message));
}
}
public class CustomerViewModel : INotifyPropertyChanged
{
private string _name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return _name; }
set { SetField(ref _name, value); }
}
// CallerMemberName fills in "Name" when called from the Name setter.
private void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return;
}
field = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Program
{
public static void Main()
{
Log.Info("Starting");
var vm = new CustomerViewModel();
vm.PropertyChanged += (sender, e) => Console.WriteLine("Changed: " + e.PropertyName);
vm.Name = "Contoso Ltd";
vm.Name = "Contoso Ltd"; // same value: no event
}
}

Output (the file name and line number depend on where you saved the file):

Program.cs:51 Main - Starting
Changed: Name
  • The attributes work only on optional parameters, and an explicitly passed argument wins. A caller can pass a wrong name on purpose or by accident.
  • CallerFilePath is the path on the build machine. Don’t show it to end users, and expect it to differ between developer and CI builds.
  • From a constructor, CallerMemberName produces .ctor; from an operator it produces the generated name, such as op_Addition.

Use nameof (C# 6) when you need the name of a member you can reference directly rather than the name of the caller. Don’t treat caller info as a security or audit trail: the caller controls the value.

The foreach variable is fresh on every iteration

Section titled “The foreach variable is fresh on every iteration”

Starting with C# 5, the iteration variable of a foreach loop is scoped to each iteration. A lambda that captures it sees the value from the iteration in which the lambda was created. Earlier compilers declared one variable for the whole loop, so every lambda saw the last value. The for loop did not change: its variable is declared once, outside the loop body.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var actions = new List<Action>();
foreach (var name in new[] { "alpha", "beta", "gamma" })
{
actions.Add(() => Console.Write(name + " "));
}
for (int i = 0; i < 3; i++)
{
actions.Add(() => Console.Write(i + " "));
}
foreach (var action in actions)
{
action();
}
Console.WriteLine();
// The foreach variable is fresh per iteration; the for variable is still shared.
}
}

Output:

alpha beta gamma 3 3 3

Microsoft lists this as a retargeting change for .NET Framework 4.5. Code that relied on the old behavior has to copy the variable to a local declared outside the loop. The for result is still a classic trap: copy i into a local inside the loop body if each lambda needs its own value.

Today you would “upgrade to C# 5” only when maintaining a very old codebase pinned to an old LangVersion. Raising LangVersion is a compile-time change; the async features also need the Task types from the target framework. The steps below are mostly about adopting async in such code.

  1. Convert APM and ContinueWith chains from the leaves upward. Make the lowest I/O call async, then each caller, until you reach an event handler or entry point.
  2. Search for .Result, .Wait() and async void after the conversion. These are the usual sources of deadlocks and unobserved exceptions.
  3. Review every foreach loop that captures its variable in a lambda if the code was written for a compiler older than C# 5.

Where it sits in the language’s evolution

Section titled “Where it sits in the language’s evolution”

C# 3 brought LINQ and lambdas, and C# 4 added dynamic and optional parameters. C# 5 used those foundations, especially lambdas and the Task type, to make asynchrony a first-class language feature. Later versions kept extending the model: C# 6 allowed await in catch and finally, C# 7.1 added async Main, and C# 8 added async streams with await foreach.

What does the compiler generate for an async method? A state machine. Local variables become fields, and each await becomes a point where the method can return and later resume. If the awaited task is already complete, execution continues synchronously without suspending.

Why can task.Result deadlock in a UI or classic ASP.NET app but not in a console app? UI and classic ASP.NET threads have a synchronization context that runs continuations on the original thread. Blocking that thread with .Result prevents the continuation from running, so neither side can proceed. A console app has no such context, so continuations run on the thread pool.

Two of the three order lookups passed to Task.WhenAll fail. What does await throw, and how do you see both failures? await rethrows only one of the exceptions, so a catch sees a single failure. The task returned by Task.WhenAll is faulted with an AggregateException holding all of them: keep a reference to that task and read its Exception.InnerExceptions in the catch, or inspect each original task’s Exception property.

How do caller info attributes differ from walking the stack? The compiler writes the values into the caller’s IL at compile time, so there is no run-time cost, and inlining or obfuscation does not change them. Stack walking happens at run time and is slower and less reliable.

Senior scenario: a service fires ten independent HTTP calls in a loop with await inside the loop. Latency is ten times one call. What do you change, and what do you watch for? Start the calls first and await Task.WhenAll, as in the sample. Then bound concurrency so a large input does not open hundreds of connections, pass a CancellationToken with a timeout, and decide whether one failure should cancel the rest.

  • C# 5 is the async release: almost everything in it serves async and await.
  • async/await turned callback chains into sequential-looking code with normal exception handling.
  • Never block on async code from a UI or request thread; use ConfigureAwait(false) in libraries; reserve async void for event handlers.
  • C# 5 can’t await in catch or finally and has no async Main.
  • foreach variables are captured per iteration from C# 5 onward; for variables are not.