Skip to content

Commit

Permalink
Add the lock for writes using the binary writer as it is not thread s…
Browse files Browse the repository at this point in the history
…afe. (#1457) (#1470)
  • Loading branch information
singhsarab authored Mar 13, 2018
1 parent 817e01f commit 851e901
Showing 1 changed file with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public class LengthPrefixCommunicationChannel : ICommunicationChannel

private readonly BinaryWriter writer;

/// <summary>
/// Sync object for sending messages
/// Write for binarywriter is NOT thread-safe
/// </summary>
private object writeSyncObject = new object();

public LengthPrefixCommunicationChannel(Stream stream)
{
this.reader = new BinaryReader(stream, Encoding.UTF8, true);
Expand All @@ -37,8 +43,13 @@ public Task Send(string data)
{
try
{
this.writer.Write(data);
this.writer.Flush();
// Writing Message on binarywriter is not Thread-Safe
// Need to sync one by one to avoid buffer corruption
lock (this.writeSyncObject)
{
this.writer.Write(data);
this.writer.Flush();
}
}
catch (Exception ex)
{
Expand Down

0 comments on commit 851e901

Please sign in to comment.