winforms - c# while loop usage -
i have general c# while loop question.
this code should continue execute after rdp session has disconnected.
when connected property changed 0 means rdp session connection has terminated. when property 1 still connected , connection has not yet terminated.
does see inherently bad code? there better way go it?
private void reconnect() { rdp1.disconnect(); // force rdp session disconnect while (rdp1.connected == 1) // true long rdp still connected { // nothing } rdp1.connect(); // execute code after while loop broken }
/**************************************************************/
here's final code used per james' answer. counter suffices timeout purpose.
int = 0; rdp1.disconnect(); while (rdp1.connected == 1) { if (i == 1000 * 10) break; else thread.sleep(100); i++; } rdp1.connect();
you should something in body of loop, or consume cpu (at least 1 core). in type of loop, you'd sleep while using system.threading.thread.sleep(100)
or something. sleep
takes number of milliseconds wait before checking while condition again. ideally, rdp object have mutex or event or block on until disconnected, wouldn't surprise me if left out.
edit: ben pointed out, it's idea have way out of loop well. (your stated answer depend on cpu speed, break in future when cpus 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 want specify timeout constant, readonly timespan
, or dynamically configurable timespan
rather magic number, , should have specific exception class case.
Comments
Post a Comment