0

Is it safe to call File.WriteAllTextAsync to write to a single file multiple times without awaiting the result, as long as all the calls are made in a single thread?

By safe I mean:

  • no IO exception will be thrown
  • afterwards the file will have the content of the last call made

This seems to run fine, but is it guaranteed to do so?

for (var i = 0; i < 1000; ++i)
{
    File.WriteAllTextAsync(fileName, i.ToString());
}
  • 1
    Try writing longer strings than 3 characters (i.e. 1,000,000 characters). It should throw an exception saying something like the file is already in use. – Sweeper Dec 29 '20 at 13:28
  • 3
    This seems like a highly artificial construct to try to reason about. Does it actually resemble a real problem you're trying to solve? I.e. why is the file involved when a single thread can just work out what content it wants to write and write it once. – Damien_The_Unbeliever Dec 29 '20 at 13:28
  • 1
    It should be awaited to avoid locking the file – Nkosi Dec 29 '20 at 13:28
  • `This seems to run fine, but is it guaranteed to do so?` No. It seems quite unwise to have two things _potentially_ running at the same time and writing to the same file. – mjwills Dec 29 '20 at 13:30
  • No it's not save. It may throw an exception when two or more tasks try to access the same file in parallel and furthermore the execution order of tasks is not guaranteed. – derpirscher Dec 29 '20 at 13:37

2 Answers2

1

No, it is not safe. You may get "File already in use " exception. Either you need await or do it synchronously.

Chandu
  • 322
  • 4
  • 13
1

No, it's not safe. It is not guaranteed that no exceptions will be thrown¹ or that all text will be written in the file. The only reason that it seems to work is because the asynchronous filesystem APIs are not implemented efficiently in .NET, and most of them block the calling thread instead of launching the operations asynchronously as they should. My suggestion is to use the synchronous API instead (File.WriteAllText).

¹ It is possible though that the thrown exceptions will remain unobserved, since the asynchronous operations are launched in a fire-and-forget fashion.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104