Flutter Isolate vs Future

▼魔方 西西 提交于 2020-01-21 06:25:47

问题


I might get the wrong idea of Isolate and Future, please help me to clear it up. Here are my understanding of both subjects.

Isolate: Isolates run code in its own event loop, and each event may run smaller tasks in a nested microtask queue.

Future: A Future is used to represent a potential value, or error, that will be available at some time in the future.

My confusions are:

  1. The doc says Isolate has it own loop? I feel like having its own event queue makes more sense to me, am I wrong?

  2. Is future running asynchronously on the main Isolate? Im assuming future task actually got placed at the end of event queue so if it will be execute by loop in the future. Correct me if im wrong.

  3. Why use Isolate when there is future? I saw some examples using Isolate for some heavy task instead of Future. But why? It only makes sense to me when future execute asynchronously on the main isolate queue.

Thanks guys, appreciate your response.


回答1:


A Future is a handle that allows you to get notified when async execution is completed. Async execution uses the event queue and code is executed concurrently within the same thread.

https://webdev.dartlang.org/articles/performance/event-loop

Dart code is by default executed in the root isolate.

You can start up additional isolates that usually run on another thread. An isolate can be either loaded from the same Dart code the root isolate was started with (with a different entry-point than main() https://api.dartlang.org/stable/2.0.0/dart-isolate/Isolate/spawn.html) or with different Dart code (loaded from some Dart file or URL https://api.dartlang.org/stable/2.0.0/dart-isolate/Isolate/spawnUri.html).

Isolates don't share any state and can only communicate using message passing (SendPort/ReceivePort). Each isolate has its own event queue.

https://webdev.dartlang.org/articles/performance/event-loop




回答2:


Isolate could be compared to Thread even if dart is not multithreaded. It has it's own memory and event loop indeed, when Futures shares the same memory

Dart is able to spawn standalone processes, called Isolates (web workers in dart2js), which do not share memory when the main program, but are able to asynchronously, in another process (effectively a thread of sorts) is able to do computations without blocking the main thread.

A Future is run inside the Isolate that called it, not necesserally the main isolate.

I recommend this article which has better explanation than me.




回答3:


In one sentence we could say,

Isolates: Dart is single-threaded but it is capable of doing multi-threading stuff using Isolates (many processes).

Future: Future is a result which is returned when dart has finished an asynchronous work. The work is generally done in that single-thread.



来源:https://stackoverflow.com/questions/52498773/flutter-isolate-vs-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!