Last active
May 14, 2020 02:42
-
-
Save Fernthedev/45d5bac76c1cc9df8a11109ce6a81fca to your computer and use it in GitHub Desktop.
Fizz Buzz demonstrates the power of async console logging in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
private static readonly Queue<Tuple<string, object[]>> PrintQueue = new Queue<Tuple<string, object[]>>(); | |
private static bool _running; | |
private static void LogAsync() | |
{ | |
while (_running) | |
{ | |
var wait = true; // To avoid waiting next cycle | |
while (PrintQueue.Count > 0) | |
{ | |
wait = false; | |
var (item1, item2) = PrintQueue.Dequeue(); | |
Console.WriteLine(item1, item2); | |
} | |
if (wait) Thread.Sleep(10); // Wait for next cycle of logs | |
} | |
} | |
// Debug variable. Switch this to see performance difference | |
private const bool WriteLineAsync = true; | |
private static void writeLine(string s, params object[] args) | |
{ | |
if (WriteLineAsync) | |
{ | |
PrintQueue.Enqueue(new Tuple<string, object[]>(s, args)); | |
} | |
else | |
{ | |
Console.WriteLine(s, args); | |
} | |
} | |
private static void Main(string[] args) | |
{ | |
_running = true; | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
if (WriteLineAsync) | |
{ | |
Console.WriteLine("Starting async console thread"); | |
new Thread(LogAsync).Start(); // Start the method async | |
} | |
const int fizzBuzz = 10000; // Testing var | |
Console.WriteLine($"Starting fizz buzz with {fizzBuzz}"); | |
for (var i = 0; i < fizzBuzz; i++) | |
{ | |
if (i % 3 == 0 && i % 5 == 0) | |
{ | |
writeLine("Fizz buzz {0}", i); | |
} else if (i % 3 == 0) | |
{ | |
writeLine("Fizz {0}", i); | |
} else if (i % 5 == 0) | |
{ | |
writeLine("Buzz {0}", i); | |
} | |
} | |
var endFizz = stopwatch.ElapsedMilliseconds; | |
while (PrintQueue.Count > 0) Thread.Sleep(10); // Wait for queue to end for the last print message | |
stopwatch.Stop(); | |
Console.WriteLine($"Finished Fizz Buzz for {fizzBuzz} in time {stopwatch.ElapsedMilliseconds}ms ({endFizz}ms for doing math)"); | |
_running = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment