Skip to content

Dart File.writeAsString() method does not write to file if await is not done immediately #36087

@renatoathaydes

Description

@renatoathaydes
  • Dart SDK Version (dart --version)

Dart VM version: 2.2.0 (Unknown timestamp) on "linux_x64"

  • Whether you are using Windows, MacOSX, or Linux (if applicable)

Linux 4.4.0-139-generic #165-Ubuntu SMP Wed Oct 24 10:58:50 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

  • Whether you are using Chrome, Safari, Firefox, Edge (if applicable)

N/A


I have the following Dart code that doesn't behave as I expected:

final File file = File("result.csv");

Future send(String message) async {
  try {
    await file.writeAsString(message + '\n',
        mode: FileMode.append, flush: true);
  } catch (e) {
    print("Error: $e");
  }
  return await file.length();
}

main() async {
  final futures = <Future>[];
  for (int i = 0; i < 100; i++) {
    futures.add(send("$i"));
  }
  for (int i = 0; i < 100; i++) {
    print(await futures[i]);
  }
}

Expected behaviour

I expected the file to be written as soon as each call to await futures[i] in the second loop returned. However this does not seem to be happening.

The file should contain one line for each index from 0 to 99.

The length of the file that is printed on each iteration of the await loop should show the file's length increasing on each call. Example:

3
6
9
12
...

Observed behaviour

Only the last call in the loop seems to write to the file. The resulting file contains a line with 99 followed by an empty line.

The print calls in the second loop always print the same file length, 3:

3
3
3
3
...

The event loop seems to be somehow merging the calls and only actually executing the last call, even though I still get 100 different futures that I await in the second loop.

The argument for each call to file.writeAsString() is different on every call, so there should be no merging happening.

If the code is modified to await on each call to send(), then the expected behaviour is observed, but that means the caller of send() cannot proceed without waiting for the file to be written to, which is not the desired behaviour (the caller does wait later, in the second loop).

Posted on StackOverflow: https://stackoverflow.com/questions/54958346/dart-file-writeasstring-method-does-not-write-to-file-if-await-is-not-done-imm


Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work onarea-vmUse area-vm for VM related issues, including code coverage, and the AOT and JIT backends.library-iotriagedIssue has been triaged by sub teamtype-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions