My understanding of async/await is, that my asynchronous methods can be performed in different threads and do not affect the responsiveness of my application.
I've implemented a simple backup/restore mechanism, where the operations take potentially quite long. While the operations are taking place, I want to show a simple waiting indicator. Therefor I implemented the following (taken from here):
showDialog(context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return PopScope(....);
});
await Future.delayed(const Duration(seconds: 2));
if (!context.mounted) return;
Navigator.of(context).pop();
This works quite well, as long I do not replace the await Future.delayed(const Duration(seconds: 2));
with some real CPU consuming method, e.g. await extractFileToDisk
.
If I do so, the dialog either
Future.delay
for a second, the waiting-indicator freezes once the CPU consuming operation has started.I personally would prefer, to push a new (dialog-) widget to the Navigator stack and do the processing there - so I could update the dialog-state (setState
) according to the progress. But I haven't found examples for that - and I'm not sure if this is the right direction.
Why do I have these problems with the GUI freeze - and how to resove it best?
You will need to explicitly start a new thread and that will hopefully sort out the issue. However, given the fact that your hardware has limited resources, it's possible that the operation you invoked asynchronously will just eat up all the resources you have. Of course, if the operation would be separated from your hardware, i.e. on a remote machine located someplace else and reached via an API, then you would have no such problems.
So the issue is that both your main thread and your resource-intensive operation runs on the same machine. You can apply an isolate, which will have its own allocated memory and call stack, so if your processor-intensive operation does not cause spikes on all processor cores that you have, then your main UI will work without issues.