Created
March 28, 2024 05:06
-
-
Save normanlmfung/e056ce45fd5ac435b1cd722de6d75fb3 to your computer and use it in GitHub Desktop.
csharp_threading
This file contains hidden or 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; | |
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