dart:io同步与异步文件操作 [英] dart:io sync vs async file operations

查看:111
本文介绍了dart:io同步与异步文件操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于文件中的 dart:io :

  • file.deleteSync() file.delete()
  • file.readAsStringSync() file.readAsString()
  • file.writeAsBytesSync(bytes) file.writeAsBytes(bytes)
  • 还有很多很多.

在同步和异步选项之间进行选择时,应牢记哪些注意事项?我似乎回想起某个地方,如果您必须等待同步完成,则同步选项会更快(例如, await file.delete()).但是我不记得在哪里看到的或者是真的.

What are the considerations that I should keep in mind when choosing between the sync and async options? I seem to recall seeing somewhere that the sync option is faster if you have to wait for it to finish anyway (await file.delete() for example). But I can't remember where I saw that or if it is true.

此方法之间是否有区别:

Is there any difference between this method:

Future deleteFile(File file) async {
  await file.delete();
  print('deleted');
}

和此方法:

Future deleteFile(File file) async {
  file.deleteSync();
  print('deleted');
}

推荐答案

让我尝试根据对我的问题的评论来总结答案.纠正我在哪里错了.

Let me try to summarize an answer based on the comments to my question. Correct me where I'm wrong.

  • async 方法中运行代码不会使其在另一个线程上运行.
  • Dart是单线程系统.
  • 代码在事件循环上运行.
  • 执行长时间运行的同步任务将阻塞系统,无论它是否处于异步方法中.
  • 隔离是一个单线程.
  • 如果要在另一个线程上运行任务,则需要在另一个隔离上运行它.
  • 启动另一个隔离程序称为生成隔离程序.
  • 在其他隔离环境上运行任务有一些选项,包括 compute IsolateChannel 编写自己的隔离通信代码.
  • 对于文件IO,同步版本比异步版本要快.
  • 对于繁重的文件IO,请首选异步版本,因为它们在单独的线程上工作.
  • 对于轻量文件IO(例如 file.exists()?),可以选择使用同步版本,因为它可能很快.
  • Running code in an async method doesn't make it run on another thread.
  • Dart is a single threaded system.
  • Code gets run on an event loop.
  • Performing long running synchronous tasks will block the system whether it is in an async method or not.
  • An isolate is a single thread.
  • If you want to run tasks on another thread then you need to run it on another isolate.
  • Starting another isolate is called spawning the isolate.
  • There are a few options for running tasks on another isolate including compute and IsolateChannel and writing your own isolate communication code.
  • For File IO, the synchronous versions are faster than the asynchronous versions.
  • For heavy File IO, prefer the asynchronous version because they work on a separate thread.
  • For light File IO (like file.exists()?), using the synchronous version is an option since it is likely to be fast.

这篇关于dart:io同步与异步文件操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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