Chris
Chris

Reputation: 27384

Does StreamWriter.Write block the current thread?

I have just noticed that the logging code in our application uses

streamWriter.Write(message);

rather than

await streamWriter.WriteAsync(message);

But will .Write actually block the current thread like a normal asynchronous operation would? In a massively concurrent system would I see a performance benefit in moving to WriteAsync?

Upvotes: 0

Views: 932

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30454

Whether the StreamWriter will block depends on what Stream it is writing its data to. If you look at the source code of StreamWriter you'll see that a Write will only add data to its internal buffer and Flush it to the Stream when this buffer is full.

The stream will copy the data to its internal buffer, and when that is full it will be flushed. The flush will do the actual saving.

If the Stream is a MemoryStream, then Flush won't cost much, but if it writes to a file, then it might take some time.

All in all, you see all the buffers involved. Designers of the Stream and StreamWriter concept already thought about improving response time way before async-await was invented.

Probably the device driver who was to do the actual writing also has some buffering mechanism to prevent that writers have to wait for the data to be actually written to the hard disk.

In theory you will gain processing time, if your StreamWriter is full, and flushes data to the Stream which is full and flushes data to the disk buffer, which is full and has to wait until the data is actually written. However I doubt whether this occurs quite often.

Upvotes: 1

A. Gopal Reddy
A. Gopal Reddy

Reputation: 380

Yes, it is better to move to WrtieAsync because the WriteAsync method enables you to perform resource-intensive I/O operations without blocking the main thread.

This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the async and await keywords in Visual Basic and C#.

https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.writeasync?view=netframework-4.7.2

Upvotes: 0

Related Questions