Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/e056ce45fd5ac435b1cd722de6d75fb3 to your computer and use it in GitHub Desktop.
Save normanlmfung/e056ce45fd5ac435b1cd722de6d75fb3 to your computer and use it in GitHub Desktop.
csharp_threading
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
// Create a concurrent queue to store lambda expressions
ConcurrentQueue<Action> actionQueue = new ConcurrentQueue<Action>();
for (int i = 0; i < 10; i++)
{
int index = i;
actionQueue.Enqueue(() =>
{
Console.WriteLine($"{index}, thread: {Thread.CurrentThread.ManagedThreadId}");
});
}
// Start a new thread to process the queue
Thread thread = new Thread(() =>
{
while (true)
{
if (actionQueue.TryDequeue(out Action action))
{
// Execute the lambda expression on the thread pool
ThreadPool.QueueUserWorkItem(_ => action());
}
else
{
// Sleep for a short duration if the queue is empty
Thread.Sleep(100);
}
}
});
thread.Start();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment