Skip to content

Commit 8946074

Browse files
committed
Sync writing to console
1 parent 62ef391 commit 8946074

File tree

2 files changed

+32
-25
lines changed

2 files changed

+32
-25
lines changed

ft/Listeners/SharedFileManager.cs

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -60,30 +60,32 @@ public void ReportNetworkPerformance()
6060
catch { }
6161

6262

63+
lock (Program.ConsoleOutputLock)
64+
{
65+
Console.Write($"{DateTime.Now}: Counterpart: ");
6366

64-
Console.Write($"{DateTime.Now}: Counterpart: ");
67+
if (IsOnline)
68+
{
69+
Console.ForegroundColor = ConsoleColor.Green;
70+
Console.Write($"{"Online",-10}");
71+
}
72+
else
73+
{
74+
Console.ForegroundColor = ConsoleColor.Red;
75+
Console.Write($"{"Offline",-10}");
76+
}
6577

66-
if (IsOnline)
67-
{
68-
Console.ForegroundColor = ConsoleColor.Green;
69-
Console.Write($"{"Online",-10}");
70-
}
71-
else
72-
{
73-
Console.ForegroundColor = ConsoleColor.Red;
74-
Console.Write($"{"Offline",-10}");
75-
}
7678

79+
var logStr = $"Rx: {receivedBandwidthStr,-12} Tx: {sentBandwidthStr,-12}";
80+
if (pingDurationStr != null)
81+
{
82+
logStr += $" {pingDurationStr}";
83+
}
7784

78-
var logStr = $"Rx: {receivedBandwidthStr,-12} Tx: {sentBandwidthStr,-12}";
79-
if (pingDurationStr != null)
80-
{
81-
logStr += $" {pingDurationStr}";
85+
Console.ForegroundColor = Program.OriginalConsoleColour;
86+
Console.WriteLine(logStr);
8287
}
8388

84-
Console.ForegroundColor = Program.OriginalConsoleColour;
85-
Console.WriteLine(logStr);
86-
8789
Thread.Sleep(reportIntervalMs);
8890
}
8991
catch (Exception ex)

ft/Program.cs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -224,18 +224,23 @@ void tearDown()
224224
public static readonly ConsoleColor OriginalConsoleColour = Console.ForegroundColor;
225225
public static readonly Random Random = new();
226226

227+
public static readonly object ConsoleOutputLock = new();
228+
227229
public static void Log(string str, ConsoleColor? color = null)
228230
{
229-
// Change color if specified
230-
if (color.HasValue)
231+
lock (ConsoleOutputLock)
231232
{
232-
Console.ForegroundColor = color.Value;
233-
}
233+
// Change color if specified
234+
if (color.HasValue)
235+
{
236+
Console.ForegroundColor = color.Value;
237+
}
234238

235-
Console.WriteLine($"{DateTime.Now}: {str}");
239+
Console.WriteLine($"{DateTime.Now}: {str}");
236240

237-
// Reset to original color
238-
Console.ForegroundColor = OriginalConsoleColour;
241+
// Reset to original color
242+
Console.ForegroundColor = OriginalConsoleColour;
243+
}
239244
}
240245
}
241246
}

0 commit comments

Comments
 (0)