【笔记】Dart 9 Concurrency

本文介绍了Dart语言对异步编程的支持,包括async/await的使用,处理异步流的方法,Isolates在并发中的应用,以及如何在Dart中进行事件处理和跨Isolate通信。此外,还讨论了性能和Isolate组的概念,以及在Flutter和Web平台上的相关限制。
摘要由CSDN通过智能技术生成

Asynchronous support

Dart对异步的天然支持,尤其在flutter中;

总得来说和Java21相似,需要注意一下 Isolate 部分关于独立堆栈的描述;

The await expression makes execution pause until that object is available.

https://dart.dev/codelabs/async-await

Future<void> checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}

try {
  version = await lookUpVersion();
} catch (e) {
  // React to inability to look up the version
}

var entrypoint = await findEntryPoint();
var exitCode = await runExecutable(entrypoint, args);
await flushThenExit(exitCode);

反复强调, await 必须在 async 修饰的函数中;

void main() async {
  checkVersion();
  print('In main: version is ${await lookUpVersion()}');
}

如果不需要返回值可以用 Future<void>

Handling Streams

await处理异步流的样板代码;

Before using await for, be sure that it makes the code clearer and that you really do want to wait for all of the stream’s results. For example, you usually should not use await for for UI event listeners, because UI frameworks send endless streams of events.

void main() async {
  // ...
  await for (final request in requestServer) {
    handleRequest(request);
  }
  // ...
}

Isolates - Concurrency in Dart

异步场景:IO,HTTP request,通信等;

const String filename = 'with_keys.json';

void main() {
  // Read some data.
  final fileData = _readFileSync();
  final jsonData = jsonDecode(fileData);

  // Use that data.
  print('Number of JSON keys: ${jsonData.length}');
}

String _readFileSync() {
  final file = File(filename);
  final contents = file.readAsStringSync();
  return contents.trim();
}


const String filename = 'with_keys.json';

void main() async {
  // Read some data.
  final fileData = await _readFileAsync();
  final jsonData = jsonDecode(fileData);

  // Use that data.
  print('Number of JSON keys: ${jsonData.length}');
}

Future<String> _readFileAsync() async {
  final file = File(filename);
  final contents = await file.readAsString();
  return contents.trim();
}

How isolates work

通常为了提高多核CPU利用率,并发场景会使用共享内存的多线程实现;

但是共享状态并发很容易引发错误,也可能导致代码复杂度提升;

https://en.wikipedia.org/wiki/Race_condition#In_software

Dart 没有用多线程,而是给每个运行一个独立的堆栈;

所以状态不共享,但是可以进行通信;

Instead of threads, all Dart code runs inside of isolates.

Each isolate has its own memory heap, ensuring that none of the state in an isolate is accessible from any other isolate.

Isolates are like threads or processes, but each isolate has its own memory and a single thread running an event loop.

Event handling

事件按照先进先出的队列顺序执行,比较自然的异步实现;

Background workers

耗时的任务可以用后台任务做,完成后会返回一个消息,和 main isolate 不共享状态;

A worker isolate can perform I/O (reading and writing files, for example), set timers, and more. It has its own memory and doesn’t share any state with the main isolate.

Code examples

If you’re using Flutter, you can use Flutter’s compute function instead of Isolate.run().

const String filename = 'with_keys.json';

void main() async {
  // Read some data.
  final jsonData = await Isolate.run(_readAndParseJson);

  // Use that data.
  print('Number of JSON keys: ${jsonData.length}');
}

Future<Map<String, dynamic>> _readAndParseJson() async {
  final fileData = await File(filename).readAsString();
  final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
  return jsonData;
}

https://github.com/dart-lang/samples/blob/main/isolates/bin/send_and_receive.dart

closure 无处不在;

const String filename = 'with_keys.json';

void main() async {
  // Read some data.
  final jsonData = await Isolate.run(() async {
    final fileData = await File(filename).readAsString();
    final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
    return jsonData;
  });

  // Use that data.
  print('Number of JSON keys: ${jsonData.length}');
}

Sending multiple messages between isolates

消息通信相关函数;

Isolate.spawn();

Isolate.exit();

ReceivePort, SendPort;

https://github.com/dart-lang/samples/blob/main/isolates/bin/long_running_isolate.dart

Performance and isolate groups

When an isolate calls Isolate.spawn(), the two isolates have the same executable code and are in the same isolate group.

共享代码;

Isolate.spawnUri() 可以拷贝一份代码,但是两个isolate不在一个组里;

Isolate.spawnUri() 比 spawn() 慢;

不同组之间传消息比在一个组里慢;

Flutter doesn’t support Isolate.spawnUri().

web 版限制好多; 不支持 isolates, 通过web worker实现类似的功能,性能一般;

The Dart web platform, however, does not support isolates.

Dart web apps can use web workers to run scripts in background threads similar to isolates.

Starting a web worker is similar to using Isolate.spawnUri to start an isolate.

Web workers don’t have an equivalent API.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值