Last active
December 7, 2023 11:04
-
-
Save pauldendulk/6a15f2c1fa81246ff9845f0975f33375 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Concurrent; | |
using System.Threading.Tasks; | |
// --- Action --- | |
var actionQueue = new ActionQueue(); | |
Console.WriteLine("No await"); | |
for (int i = 0; i < 10; i++) | |
actionQueue.PutOnQueue(() => DoAsync()); | |
Console.ReadLine(); | |
Console.WriteLine("Async await in lambda"); | |
for (int i = 0; i < 10; i++) | |
actionQueue.PutOnQueue(async () => await DoAsync()); | |
Console.ReadLine(); | |
Console.WriteLine("Wait() in lambda"); | |
for (int i = 0; i < 10; i++) | |
actionQueue.PutOnQueue(() => DoAsync().Wait()); | |
Console.ReadLine(); | |
// Console.WriteLine("Method group"); | |
// Does not compile because DoSomething returns Task instead of void: actionQueue.PutOnQueue(DoSomething); | |
// Console.ReadLine(); | |
// --- Func<Task> --- | |
var funcOfTaskQueue = new FuncOfTaskQueue(); | |
Console.WriteLine("No await"); | |
for (int i = 0; i < 10; i++) | |
funcOfTaskQueue.PutOnQueue(() => DoAsync()); | |
Console.ReadLine(); | |
Console.WriteLine("Async await in lambda"); | |
for (int i = 0; i < 10; i++) | |
funcOfTaskQueue.PutOnQueue(async () => await DoAsync()); | |
Console.ReadLine(); | |
// Console.WriteLine("Wait() in lambda"); | |
// for (int i = 0; i < 10; i++) | |
// Does not compile because Wait() does not return a Task: funcOfTaskQueue.PutOnQueue(() => DoSomething().Wait()); | |
// Console.ReadLine(); | |
Console.WriteLine("Method group"); | |
for (int i = 0; i < 10; i++) | |
funcOfTaskQueue.PutOnQueue(DoAsync); | |
Console.ReadLine(); | |
async Task DoAsync() | |
{ | |
Console.WriteLine("Start of method"); | |
await Task.Delay(100); | |
Console.WriteLine("End of method"); | |
} | |
class ActionQueue | |
{ | |
BlockingCollection<Action> _queue = new(); | |
public ActionQueue() | |
=> _ = Task.Run(QueueHandlingLoop); | |
private void QueueHandlingLoop() | |
{ | |
foreach (var action in _queue.GetConsumingEnumerable()) | |
{ | |
action(); | |
} | |
} | |
public void PutOnQueue(Action action) { | |
_queue.Add(action); | |
} | |
} | |
class FuncOfTaskQueue | |
{ | |
BlockingCollection<Func<Task>> _queue = new(); | |
public FuncOfTaskQueue() | |
=> _ = Task.Run(QueueHandlingLoop); | |
private async Task QueueHandlingLoop() | |
{ | |
foreach (var action in _queue.GetConsumingEnumerable()) | |
{ | |
await action(); | |
} | |
} | |
public void PutOnQueue(Func<Task> action) | |
{ | |
_queue.Add(action); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment