为什么Future会阻止ui,但网络请求却不会颤动 [英] Why Future block the ui but network requests don't in flutter

查看:176
本文介绍了为什么Future会阻止ui,但网络请求却不会颤动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Future将在事件队列中运行。但是事件队列也在主隔离中运行,如果将来我执行一些繁重的任务(例如,计算总和从1到1000000),它将阻塞我的ui代码。
但将来网络操作不会阻止ui(例如await httpClient.getUrl(uri))。
为什么将来使用网络请求会花费几秒钟而不会阻塞UI,而计算操作会阻塞UI?

I know Future will run in event queue.But event queue are also running on main isolate, if i do some heavy task (for example, calculate sum from 1 to 1000000) in future, it will block my ui code. But Future in network operation will not block ui (such as await httpClient.getUrl(uri)). Why does a network request using future take several seconds without blocking the UI, while computational operations block the UI?

@override
void initState() {
super.initState();
Future((){
  var result;
  for (var i = 0; i < 1000000; ++i) {
    result = 'result is $i';
  }
  print(result);
});

}

推荐答案

Dart中的隔离是单线程的。隔离者一次只能做某事。

Isolates in Dart are single-threaded. An isolate can do only thing at a time.

异步功能基本上是合作多任务。函数必须 yield (通常通过 await )以允许其他操作在隔离中执行。

Asynchronous functions are basically a form of cooperative multitasking. A function must yield (usually via await) to allow other operations to execute in the isolate.

您的计算不会产生结果,因此它必须完整运行,然后UI才能继续处理事件,并且UI将无响应。如果您更改了它:

Your computation doesn't yield, so it must run in its entirety before the UI can resume processing events, and the UI will be unresponsive. If you altered it:

Future(() async {
  var result;
  for (var i = 0; i < 1000000; ++i) {
    result = 'result is $i';
    await Future.delayed(Duration.zero);
  }
  print(result);
});

然后,您应该发现UI可以定期处理事件,并且应该保持响应状态。 (请注意,由于额外的额外开销,您的计算将花费更长的时间。)

then you should find that the UI can process events regularly and should have the appearance of remaining responsive. (Note that your computation will take much longer to complete because of the additional extra overhead.)

这篇关于为什么Future会阻止ui,但网络请求却不会颤动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆