Skip to content

Instantly share code, notes, and snippets.

@kentkost
Created April 11, 2020 08:48
Show Gist options
  • Save kentkost/45669685726296ddcc163bd24966b4f5 to your computer and use it in GitHub Desktop.
Save kentkost/45669685726296ddcc163bd24966b4f5 to your computer and use it in GitHub Desktop.
Threading using a delegate ThreadStart to control flow #thread #threadstart #semaphore
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Threading
{
class Program
{
public static Semaphore semaphore = new Semaphore(2, 3);
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++) {
ThreadStart ts = delegate
{
Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter into Critical Section for processing");
try {
semaphore.WaitOne();
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork) {
DoMoreWork("param1", "param2");
}
}
finally {
semaphore.Release();
}
};
Thread t = new Thread(ts);
t.Name = "Thread " + i;
t.Start();
}
Console.ReadKey();
}
static bool DoWork(string s1, string s2, string s3)
{
Thread.Sleep(2000);
Console.Write(Thread.CurrentThread.Name + " says: ");
Console.WriteLine(s1 + s2 + s3);
return true;
}
static void DoMoreWork(string s1, string s2)
{
Thread.Sleep(2000);
Console.Write(Thread.CurrentThread.Name + " says: ");
Console.WriteLine(s1 + s2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment