Skip to content

Commit ffb5766

Browse files
committed
Fix potential stack overflow in Record app
1 parent b00d4bc commit ffb5766

1 file changed

Lines changed: 12 additions & 28 deletions

File tree

Apps/Record/Program.cs

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System;
2-
using System.Collections.Generic;
2+
using System.Collections.Concurrent;
33
using System.Diagnostics;
44
using System.IO;
55
using System.Threading;
@@ -21,9 +21,7 @@ class Message
2121

2222
class Program
2323
{
24-
static readonly Queue<Message> _fileWriteQueue = new Queue<Message>();
25-
26-
static readonly object _queueLock = new object();
24+
static readonly ConcurrentQueue<Message> _fileWriteQueue = new ConcurrentQueue<Message>();
2725

2826
static readonly Stopwatch _stopWatch = new Stopwatch();
2927

@@ -195,10 +193,7 @@ private static void QueueMessage(PacketType packetType, byte[] data)
195193
Type = packetType
196194
};
197195

198-
lock (_queueLock)
199-
{
200-
_fileWriteQueue.Enqueue(packetData);
201-
}
196+
_fileWriteQueue.Enqueue(packetData);
202197

203198
if (!_isWritingToFile)
204199
{
@@ -219,33 +214,22 @@ private static void WriteData()
219214
{
220215
try
221216
{
222-
Message packet = null;
223-
224-
lock (_queueLock)
225-
{
226-
if (_fileWriteQueue.Count > 0)
227-
{
228-
packet = _fileWriteQueue.Dequeue();
229-
}
230-
}
231-
232-
if (packet == null)
217+
while (_fileWriteQueue.TryDequeue(out var packet))
233218
{
234-
_isWritingToFile = false;
235-
return;
219+
_binaryWriter.Write((byte)packet.Type);
220+
_binaryWriter.Write(packet.Timestamp);
221+
_binaryWriter.Write(packet.Data.Length);
222+
_binaryWriter.Write(packet.Data);
236223
}
237-
238-
_binaryWriter.Write((byte)packet.Type);
239-
_binaryWriter.Write(packet.Timestamp);
240-
_binaryWriter.Write(packet.Data.Length);
241-
_binaryWriter.Write(packet.Data);
242-
243-
WriteData();
244224
}
245225
catch (Exception ex)
246226
{
247227
Console.WriteLine(ex);
248228
}
229+
finally
230+
{
231+
_isWritingToFile = false;
232+
}
249233
}
250234
}
251235
}

0 commit comments

Comments
 (0)