Skip to content

Commit 766b9ac

Browse files
johnml1135jasonleenaylor
authored andcommitted
fix: restore async WriteAsync with proper write chaining
Address PR review feedback: - Restore fire-and-forget WriteAsync per reviewer request (jasonleenaylor) - Chain writes via ContinueWith/Unwrap to prevent overlapping async writes on the same stream - Use bytes.Length for correct byte count (fixes truncation on Windows where Environment.NewLine is 2 chars) - Dispose waits for pending writes via GetAwaiter().GetResult() before flushing and closing the stream - Remove unnecessary Thread.Sleep(200) from test; Dispose guarantees writes are complete
1 parent 2fa4912 commit 766b9ac

2 files changed

Lines changed: 8 additions & 5 deletions

File tree

src/SIL.LCModel/FileTransactionLogger.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
using System.Diagnostics;
33
using System.IO;
44
using System.Text;
5+
using System.Threading.Tasks;
56

67
namespace SIL.LCModel
78
{
89
internal class FileTransactionLogger : ITransactionLogger, IDisposable
910
{
1011
private readonly object m_lock = new object();
1112
private FileStream m_stream;
13+
private Task m_lastWrite = Task.CompletedTask;
1214
private bool m_disposed;
1315

1416
internal FileTransactionLogger(string filePath)
@@ -30,8 +32,9 @@ public void AddBreadCrumb(string description)
3032
if (m_disposed)
3133
return;
3234
var bytes = Encoding.UTF8.GetBytes(description + Environment.NewLine);
33-
m_stream.Write(bytes, 0, bytes.Length);
34-
m_stream.Flush();
35+
m_lastWrite = m_lastWrite.ContinueWith(_ =>
36+
m_stream.WriteAsync(bytes, 0, bytes.Length),
37+
TaskContinuationOptions.ExecuteSynchronously).Unwrap();
3538
}
3639
}
3740

@@ -42,6 +45,8 @@ protected virtual void Dispose(bool disposing)
4245
{
4346
if (!m_disposed)
4447
{
48+
try { m_lastWrite?.GetAwaiter().GetResult(); }
49+
catch { /* best-effort: don't let a failed write prevent disposal */ }
4550
m_stream?.Flush();
4651
m_stream?.Dispose();
4752
m_stream = null;

tests/SIL.LCModel.Tests/FileTransactionLoggerTests.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,7 @@ public void AddBreadCrumb_WritesFullMessageIncludingNewline()
7373
logger.AddBreadCrumb(message);
7474
}
7575

76-
// Wait briefly for async write, then read
77-
System.Threading.Thread.Sleep(200);
78-
76+
// Dispose flushes the stream, so the file is readable immediately.
7977
string content = File.ReadAllText(m_tempFile, Encoding.UTF8);
8078
string expected = message + Environment.NewLine;
8179
Assert.AreEqual(expected, content,

0 commit comments

Comments
 (0)