Gabriel Gabriel - 1 year ago 142
Dart Question

Is Dart's async really async?

Given the following code

import 'dart:async';

var total = 0;
final iterations = 10000000;

Future add() async {
print('starting add -> $total');

for (var i = 0; i < iterations; i++) {
total += 1;

print('ending add -> $total');

Future sub() async {
print('starting sub -> $total');

for (var i = 0; i < iterations; i++) {
total -= 1;

print('ending sub -> $total');

void main(List<String> args) {

which generates the following output

starting add -> 0
ending add -> 10000000
starting sub -> 10000000
ending sub -> 0

I wonder if
calls are really executed in an async fashion.

It looks like all
methods run in a second thread which is always the same, so they are async for their callers, but not for each other.

Am I right? If so, how can I execute multiple functions in an really async fashion (just like creating new threads)?

Answer Source

This is how async works. There is only one thread and an event queue where tasks are enqueued. When the previous sync execution is completed, then the next task in the queue is executed.

If you need parallel execution you can leverage isolates.

See also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download