Condition false, but code inside the if statement executed

前端 未结 3 1854
醉梦人生
醉梦人生 2020-12-19 22:55

I have the following method:

public bool ConnectAsync()
{
    if (IsConnected)
        throw new InvalidOperationException(\"Socket is already connected\");
         


        
相关标签:
3条回答
  • 2020-12-19 23:24

    This is probably an issue with the debugger and multiple threads, try putting the lock around the outside of the if statement rather than inside the property.

    0 讨论(0)
  • 2020-12-19 23:27

    This answer explained the problem I was having: https://stackoverflow.com/a/27552124/1830461

    Something of this format compiled to 64-bit can cause the debugger to step into the if statement:

            if (falseCondition) 
                throw new Exception(); 
            try { }  catch { }
    

    It's a bug in Visual Studio. The code isn't actually executed. The solution is to just ignore it and continue stepping through the code. Putting a lock statement on it fixes it, because it is no longer in that format.

    0 讨论(0)
  • 2020-12-19 23:32

    The Expression window you have in the debugger is the one triggering the exception, not your code. Remove expressions (or watch) and it should work as expected.

    0 讨论(0)
提交回复
热议问题