15

When you turn on the "Break when an exception is thrown" feature in the Visual Studio debugger it breaks everywhere for selected exception types. The way to tell it not to break in a specific method is to decorate these methods with DebuggerStepThrough attribute (or DebuggerHidden).

This, evidently, doesn't work for an async method for some reason. Here's a snippet that reproduces the issue. The debugger will break inside the TestAsync even though it's marked with the attributes and it will not break inside Test as excepted ( the only difference between them is the first is marked with the async keyword):

public class Attributes
{
    public async Task Run()
    {
        await TestAsync();
        await Test();
    }

    [DebuggerHidden]
    [DebuggerStepThrough]
    public async Task TestAsync()
    {
        try
        {
            throw new Exception("Async");
        }
        catch
        {
        }
        await Task.Delay(100);
    }

    [DebuggerHidden]
    [DebuggerStepThrough]
    public Task Test()
    {
        try
        {
            throw new Exception("sync");
        }
        catch
        {
        }
        return Task.Delay(100);
    }
}

So, is this behavior intended? Is it a bug? Is there a workaround?

3
  • 2
    It is a fairly inevitable flaw in the way the C# compiler implements asynch, your method is rewritten into a hidden class. Which does not get those same attributes. Use ildasm.exe to look under the hood. Jun 26, 2014 at 14:53
  • @HansPassant I originally thought it doesn't work only after an await is used (ie the continuation), but apparently it always fails.
    – i3arnon
    Jun 26, 2014 at 14:55
  • It works to me in the .NET 6 with Jetbrains Rider even in async code. Jan 10 at 11:30

1 Answer 1

6

Attributes don't play well with async/await since async methods get re-written under the covers--and the attributes do not follow. See https://stackoverflow.com/a/22412597/495262 for a similar situation.

2
  • 1
    Note that DebuggerStepThrough and DebuggerHidden are subject to interpretation by a particular debugger. They have no particular meaning to the CLR. They may well work as documented in future updates of VS.
    – Eric J.
    Jul 14, 2014 at 21:46
  • @EricJ. It may, but as of 2024 (VS 17.8) it still doesn't. Feb 25 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.