-1

To reproduce: create any .NET 7 console project with Visual Studio 2022. Put a breakpoint at the line on the closing bracket. Start debugging, you'll observe the breakpoint being hit. I expect a press of Continue(F5) will run through this line but actually, it will be hit again.

public static class MainClass
{
    public static void Main()
    {
        DoTask();
    }

    static void DoTask()
    {
        using ManualResetEvent mre = new(initialState: true);
        mre.WaitOne(500);
    } // Hits twice
}

This will not happen if the method is async.

public static class MainClass
{
    public static async Task Main()
    {
        await DoTaskAsync();
    }

    static async Task DoTaskAsync()
    {
        using ManualResetEvent mre = new(initialState: true);
        mre.WaitOne(500);
        await Task.CompletedTask;
    } // Won't hit twice
}

I wonder using the "using declaration" with ManualResetEvent has any adverse implications? Hitting the break point twice is not a good sign to me.

  • Code edited to not use Top Level Statements
Lionet Chen
  • 832
  • 11
  • 26
  • The first code you are not waiting for the task to be completed. – jdweng Aug 24 '23 at 12:25
  • 2
    I think it's a bug when you are using the new Top Level Statements style, along with a Local Function, and the breakpoint is at the end of the local function which is also the end of the file. It's just setting two separate breakpoints, both of which point to the same line in the source code, but different points in the compiled code. If you write these as a proper class with two separate functions I don't think this happens. – Charlieface Aug 24 '23 at 12:25
  • 1
    @jdweng The first code is not calling an `async` function so no `await` needed. – Charlieface Aug 24 '23 at 12:27
  • In first method DoTask() is running Async (returning before completing). So your code is probably running the posted code more. Put break point on DoTask() and see if you get there twice. – jdweng Aug 24 '23 at 12:40
  • Sorry I was being lazy. I got rid of the Top-level statement. The scenario can still be reproduced. – Lionet Chen Aug 24 '23 at 12:41
  • 1
    it's as @Charlieface explained. It's even more clear when showing `Disassembly` with 2 breakpoints being set there and only one in the source code. – Paweł Łukasik Aug 24 '23 at 20:40
  • Interestingly, this does not occur in Rider. Breakpoint is hit only once – Paweł Łukasik Aug 25 '23 at 08:27
  • @PawełŁukasik Thanks for the tip about Disassembly. I did find that when hitting the line twice, the breakpoint in the IL code is different for each hit. I don't know if Rider is doing something to combine the hits. – Lionet Chen Aug 27 '23 at 08:04

0 Answers0