Reputation: 19
import 'dart:io';
main() async {
await loop();
while(true){
print('Your input:${stdin.readLineSync()}');
}
}
loop(){
print('stuck');
//Future.delayed(Duration(days:5),(){});//works fine
//while(true);//does not work
}
Why cannot users input anything when while(true) is being executed inside loop(), instead, Future. delayed works fine with stdin?
Upvotes: 0
Views: 1031
Reputation: 71723
Dart is single-threaded. That means that at most one piece of Dart code is running at a time (per isolate if you have isolates).
Code like while(true);
is a tight loop that never stops. No other code will run in the same isolate until the loop ends, and the loop never ends. This is busy waiting, and it does not give other code time to run.
You never even get to the part of your code which calls stdin.readLineSync()
.
The await
in front of loop()
does nothing, because the code never gets to it. It calls loop
and stays there forever.
If you create a Future.delayed(...)
, then ... it doesn't actually do anything. You are not returning it, so the await
won't be waiting for it to complete. All you do is to create a timer, create a Future
object, and when the timer runs out, something will happen which will complete the future. If you return the future, then the await
will wait for that.
What did you want or expect this code to do?
Upvotes: 1