Home > front end >  Is it safe to call WriteLineAsync again, before the previous Task is complete?
Is it safe to call WriteLineAsync again, before the previous Task is complete?

Time:09-16

I'd like to call StreamWriter::WriteLineAsync() on a file, frequently, without blocking. After some research, I find that WriteLineAsync() actually often performs synchronously, just buffering the data and returning a Completed Task. But occasionally it wont, and I understand there's lots of clever and not entirely deterministic optimisations to do with buffer sizes and flush intervals to deal with the vagaries of file systems. At this stage I don't know often I'll be filling that buffer, or whether there might other reasons WriteLineAsync() actually runs async, or whether switching .NET versions will change that.

So I'd like to be prepared up front. I figure I have two options:

  1. If safe to do so, just call WriteLineAsync() as often as I like, potentially before the previous Task is complete. Then, if necessary, perhaps occasionally check for resource exhaustion somehow, and dial back my writing to accommodate.
  2. If not, wrap my async method that calls WriteLineAsync() in a method that keeps a hold of the Task from the last time it was called, and throttles subsequent calls if the previous Task hasn't completed.

I suspect, given I can't see throngs of confused programmers who are crashing the system by smashing out WriteLineAsync() calls, that it's all magically taken care of. But I can't find any confirmation that is the case. So is it safe to call WriteLineAsync() repeatedly, without thought to the plight of the previous call?

CodePudding user response:

From the documentation of the StreamWriter.WriteLineAsync method:

Exceptions

ObjectDisposedException
The stream writer is disposed.

InvalidOperationException
The stream writer is currently in use by a previous write operation.

So apparently the answer is no. Starting a new asynchronous operation before a previous one has completed is an error.

  • Related