Lets Understand One of the important part of Threading .
Auto-Reset-Event class is one of the most important part of the Threading which helps to Manage Synchronize threading with the help of Signals.
Also we will discuss WaitOne() and Set() which will use in AutoResetEvent.
AutoResetEvent just like ManualResetEvent with a small difference which we will discuss here.
This use System.Threading namespace.
AutoResetEvent Flow
AutoResetEvent |
Description
- Create a thread as below.
Thread thread1 = new Thread(autoresetevent);
thread1.Start();
- Create a function called autoresetevent which has below code.
public static void autoresetevent()
{
Console.WriteLine("Thread Started--1.....");
autoevent.WaitOne(); //Used to stop executing thread
Console.WriteLine("Thread ended--1.....");
Console.WriteLine("Thread Started--2.....");
autoevent.WaitOne();//Used to stop executing thread
Console.WriteLine("Thread ended--2.....");
}
{
Console.WriteLine("Thread Started--1.....");
autoevent.WaitOne(); //Used to stop executing thread
Console.WriteLine("Thread ended--1.....");
Console.WriteLine("Thread Started--2.....");
autoevent.WaitOne();//Used to stop executing thread
Console.WriteLine("Thread ended--2.....");
}
- Autoresetevent has two methods
b. Set()
WaitOne() used to keep the thread in a halt mode.
Set() used to give the signal to continue execution which is in halt mode.
Lets Understand with a complete program.
class AutoResetEvent_Example
{
static AutoResetEvent autoevent = new AutoResetEvent(false);
public static void Main()
{
Thread thread1 = new Thread(autoresetevent);
thread1.Start();
Console.ReadKey();
autoevent.Set();
Console.ReadKey();
autoevent.Set();//For auto reset same number of "Set" //required for each "WaitOne"
Console.ReadKey();
}
public static void autoresetevent()
{
Console.WriteLine("Thread Started--1.....");
autoevent.WaitOne();
Console.WriteLine("Thread ended--1.....");
Console.WriteLine("Thread Started--2.....");
autoevent.WaitOne();
Console.WriteLine("Thread ended--2.....");
}
}
In the above example we can check the below statement
static AutoResetEvent autoevent = new AutoResetEvent(false);
Constructor of the AutoResetEvent class can be True or False.
True-When the initial state is signaled
False- When the initial state is not signaled
Program OutPut
In the above output, thread stop executing after the 1st statement.
Once you press ENTER then next 2 statement will be executed and after that last statement gets executed.
When the constructor value of the AutoResetEvent class is True then 3 statement will execute when we run the application , after that last statement will be executed.
Conclusion
- AutoResetEvent does not allow the thread to execute complete statement at a time.
- WaitOne() used to keep the thread in a halt mode.
- Set() used to give the signal to continue execution which is in halt mode.
- For Each WaitOne() , Set() is required to continue the thread.
No comments:
Post a Comment