dart:io sync vs async file operations

痞子三分冷 提交于 2021-02-19 09:04:46

问题


There are a number of sync and async operations for files in dart:io:

  • file.deleteSync() and file.delete()
  • file.readAsStringSync() and file.readAsString()
  • file.writeAsBytesSync(bytes) and file.writeAsBytes(bytes)
  • and many, many more.

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');
}

and this method:

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

回答1:


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

  • 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.

Further reading

  • Isolates and Event Loops
  • Single Thread Dart, What? — Part 1
  • Single Thread Dart, What? — Part 2
  • avoid_slow_async_io lint


来源:https://stackoverflow.com/questions/61169619/dartio-sync-vs-async-file-operations

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