In C#, what changes when a method returns another method's Task directly instead of awaiting it, for exceptions and for a using block around the call?
answer
- the method ends at return
- the scope closes early
- where the exception lands
- pass-through versus wrapper
basics
~20 sReturning the inner task without async and await ends the method at its return: a using block disposes the resource mid-operation, a catch misses the task's later failures, and the method's own exceptions throw at the call rather than faulting the task.
solid answer
~40 sReturning `inner.FetchAsync()` directly, often called **eliding** `async` and `await`, makes the outer method an ordinary method: it runs, returns the unfinished task, and is gone. Three things follow. A `using` block or `finally` around the return runs **when the method returns**, not when the task completes, so `connection` can be disposed mid-request and the operation fails with `ObjectDisposedException`. A `try`/`catch` around it only sees exceptions thrown while creating the task, never the task's later failure. And an exception from the method's own code, such as argument validation, is thrown **at the call**, whereas in an `async` method it is stored in the task and rethrown at `await`. Eliding saves a state machine and is fine for a one-line pass-through; anything with `using`, `try` or work after the call should `return await`.
code
csharp · 35 linesConsole.WriteLine(await ReadForecastAwaitedAsync());
try
{
Console.WriteLine(await ReadForecastDirectAsync());
}
catch (ObjectDisposedException ex)
{
Console.WriteLine($"ObjectDisposedException: {ex.ObjectName} was used after Dispose");
}
static async Task<string> ReadForecastAwaitedAsync()
{
using var connection = new UpstreamConnection();
return await connection.FetchAsync(); // Dispose runs after FetchAsync has finished
}
static Task<string> ReadForecastDirectAsync()
{
using var connection = new UpstreamConnection();
return connection.FetchAsync(); // Dispose runs as this line returns the unfinished task
}
sealed class UpstreamConnection : IDisposable
{
private bool _disposed;
public async Task<string> FetchAsync()
{
await Task.Delay(100); // waiting for the upstream service
ObjectDisposedException.ThrowIf(_disposed, this);
return "Oslo: 7 C";
}
public void Dispose() => _disposed = true;
}go deeper
Recall that a method without async ends at its return statement, even if the task it returned is still running.
Explain why a using block disposes early when the task is returned directly, and where validation exceptions surface in an async versus a plain method.
Diagnose ObjectDisposedException and missed catch blocks caused by an elided await, and state a review rule for when eliding is safe.
Decide whether eliding is worth allowing in a codebase at all, weighing a small saving against bugs that appear only under real I/O timing.
## Two ways to forward a task A method that calls another asynchronous method and passes its result on can be written two ways. ```csharp // Awaiting: the method is async and finishes when the inner task does static async Task<string> ReadAwaitedAsync() => await upstream.FetchAsync(); // Eliding: an ordinary method that hands back the inner task static Task<string> ReadDirectAsync() => upstream.FetchAsync(); ``` For this one-line case they behave the same for the caller. Everything changes as soon as the method has a resource, a `try` block, or code of its own. The key fact is simple: **a method without `async` ends at its `return` statement**, while an `async` method ends when its last `await` completes. | Aspect | `return await inner()` in an `async` method | `return inner()` in a plain method | |---|---|---| | When `using` disposes and `finally` runs | after the inner task completes | as soon as the task is returned | | What a surrounding `catch` sees | the inner task's failures too | only exceptions thrown before the return | | Where the method's own exceptions go | stored in the returned task | thrown at the call | | State machine | generated | none | ## Difference 1: using and finally blocks The first code example models the weather client opening a connection to an upstream service. `UpstreamConnection.FetchAsync` waits for the response and then checks whether the connection has been disposed, using `ObjectDisposedException.ThrowIf`. 1. In `ReadForecastAwaitedAsync`, the method is `async`. It awaits `FetchAsync`, so the method body, including the scope of `using var connection`, lasts until the response has been read. `Dispose` runs afterwards, and the forecast prints. 2. In `ReadForecastDirectAsync`, the method is not `async`. `connection.FetchAsync()` starts the request and returns an unfinished task; the `return` statement then leaves the method, the `using` declaration's scope ends, and `Dispose` runs at once. When the response arrives, `FetchAsync` finds its connection disposed and throws. The output shows the first call succeeding and the second failing with `ObjectDisposedException`. Real resources such as a database connection, a file stream or a transaction fail the same way, usually far less clearly. A `finally` block or any other cleanup at the end of the method behaves identically, and so does a `catch`: it cannot handle a failure that happens after the method has already returned. ## Difference 2: when exceptions surface The second code example validates the city name with `ArgumentException.ThrowIfNullOrEmpty`, once in an `async` method and once in a plain method that then forwards a task. - The `async` version **does not throw at the call**. The compiler-generated code catches the exception and stores it in the returned task, which is already faulted (`IsFaulted = True`), and it is rethrown only when the caller awaits. - The plain version **throws at the call**, before any task exists. Neither is wrong in itself. The Task-based Asynchronous Pattern says usage errors such as a bad argument may be thrown directly from the call, while every other failure belongs in the task. The danger is changing one form into the other during a refactor: a caller whose `try` wraps only the `await`, or one that starts several tasks and awaits them later, sees the exception at a different line than before. The usual way to get eager validation together with an `async` body, a plain method that validates and then calls a private `async` local function, is covered with local functions. ## What eliding actually saves - The compiler does not generate a state machine or builder for the method, which saves an allocation on the slow path and a little work on every call. - One frame fewer: the eliding method does not appear in the stack trace of an exception the inner task raises later, because it had already returned. That saving is small next to a network call, and the generated state machine itself is the subject of its own lesson. ## A rule of thumb for code review 1. **Elide** only in a true pass-through: a single call whose task is returned unchanged, with no `using`, no `try`, and no code after it. 2. **Use `return await`** whenever the method owns a resource, catches or cleans up, or does anything after the inner call. 3. When converting between the two, **check exception timing** for callers that start the task on one line and await it on another.
- Does a try/catch around `return inner.FetchAsync();` in a non-async method catch the request's failure?No. The `try` block ends when the method returns the unfinished task, so the `catch` only sees exceptions thrown while starting the operation. A failure that occurs later is stored in the task and reaches whoever awaits it. To handle it in this method, make the method `async` and `return await` inside the `try`.
- Should argument validation throw at the call or fault the task?The Task-based Asynchronous Pattern allows usage errors, such as a null or empty argument, to be thrown directly from the call, and wants every other failure placed in the returned task. An `async` method stores even its validation exceptions in the task, so code that needs eager checks validates in a plain method and then calls an async helper.
- Is eliding async and await worth doing for performance?Occasionally, in a hot pass-through method called very often, where skipping the state machine measurably helps. For most application code the saving is negligible next to the I/O being awaited, and the disposal and exception-timing differences make `return await` the safer default.
- return task and return await task behave identically apart from speed
- A using block waits for a returned task to finish before disposing
- An async method throws its argument exceptions at the call site
- Eliding async and await should be applied everywhere because it is faster
- A try/catch around return SomethingAsync() catches the task's later failure