Last active
April 11, 2020 08:37
-
-
Save kentkost/0e4cf366082138fe2457158c3016b981 to your computer and use it in GitHub Desktop.
Threads with ParameterizedThreadStart #threads
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.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++) { | |
ParameterizedThreadStart pt = new ParameterizedThreadStart(DoSomeTask); | |
//Could do automatic casting by simply passing new Thread(DoSomeTask); | |
Thread threadObject = new Thread(pt) { | |
Name = "Thread " + i | |
}; | |
threadObject.Start(i); | |
} | |
Console.ReadKey(); | |
} | |
static void DoSomeTask(object id) | |
{ | |
Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter into Critical Section for processing"); | |
try { | |
//Blocks the current thread until the current WaitHandle receives a signal. | |
semaphore.WaitOne(); | |
Console.WriteLine("Success: " + Thread.CurrentThread.Name + " is Doing its work"); | |
Thread.Sleep(5000); | |
Console.WriteLine(Thread.CurrentThread.Name + "Exit."); | |
} | |
finally { | |
//Release() method to releage semaphore | |
semaphore.Release(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment