Page 1 of 1

Dart Parallel Execution

Posted: 22 Jan 2021, 08:48
by brid.surapol

Code: Select all

import 'dart:io';

void main() {
  performTasks2();
}

void performTasks2() async {
  task1();
  Future<String> result2 = task2();
  Future<String> result22 = task22();
  Future<String> result222 = task222();
  task3();

  String str2 = await result2;
  String str22 = await result22;
  String str222 = await result222;

  print('$str2 $str22 $str222');
}

void performTasks() async {
  task1();

  List<Future<String>> futures = [
    task2(),
    task22(),
    task222(),
  ];

  List<String> results = await Future.wait<String>(futures);
  // List results = await Future.wait([task2(), task22()]);

  print(results.runtimeType);
  print(results);

  task3();
}

void task1() {
  String result = 'task 1 data';
  print('Task 1 complete');
}

Future<String> task2() async {
  Duration dur = Duration(seconds: 3);
  String result;

  await Future.delayed(dur, () {
    result = 'task 2 data';
    print('Task 2 complete');
  });

  return result;
}

Future<String> task22() async {
  Duration dur = Duration(seconds: 4);
  String result;

  await Future.delayed(dur, () {
    result = 'task 22 data';
    print('Task 22 complete');
  });

  return result;
}

Future<String> task222() async {
  Duration dur = Duration(seconds: 2);
  String result;

  await Future.delayed(dur, () {
    result = 'task 222 data';
    print('Task 222 complete');
  });

  return result;
}

void task3() {
  String result = 'task 3 data';
  print('Task 3 complete');
}