Search code examples
c#winformsrdpmstsc

c# while loop usage


I have a fairly general c# while loop question.

This code should continue to execute only after the RDP session has truly disconnected.

When the Connected property is changed to 0 it means that the RDP session connection has truly terminated. When the property is 1 it is still connected and the connection has not yet terminated.

Does anyone see anything inherently bad about this code? Is there a better way to go about it?

private void Reconnect()
{
    rdp1.Disconnect(); // force the RDP session to disconnect
    while (rdp1.Connected == 1) // true as long as RDP is still connected
    {
        // do nothing
    } 
    rdp1.Connect(); // execute this code after while loop is broken
}

/**************************************************************/

Here's the final code I used per James' answer. The counter suffices as the timeout for my purpose.

            int i = 0;
            rdp1.Disconnect();
            while (rdp1.Connected == 1)
            {
                if (i == 1000 * 10) break;
                else Thread.Sleep(100);
                i++;
            }
            rdp1.Connect();

Solution

  • You should do something in the body of loop, or it will consume all your CPU (at least for one core). Usually in this type of loop, you'd sleep for a while using System.Threading.Thread.Sleep(100) or something. Sleep takes the number of milliseconds to wait before checking the while condition again. Ideally, the RDP object would have a mutex or event or something you could just block on until it was disconnected, but it wouldn't surprise me if they left that out.

    EDIT: As Ben pointed out, it's always a good idea to have a way out of the loop as well. Something like this (your stated answer will depend on the CPU speed, which could break in the future when CPUs are much faster):

    DateTime stop = DateTime.UtcNow.AddSeconds(30);
    while (rdp1.Connected)
    {
        if (DateTime.UtcNow > stop) throw new ApplicationException ("RDP disconnect timeout!");
        System.Threading.Thread.Sleep (100);
    }
    

    Of course you will probably want to specify the timeout with a constant, a readonly TimeSpan, or a dynamically configurable TimeSpan rather than a magic number, and you should probably have a specific exception class for this case.