if a threadA is sleeping, how will another thread threadB call threadA to start ? Please provide an example if possible.
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
Suspends the current thread for the specified number of milliseconds.
Steps to create a thread in a C# Program: First of all import System. Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime. Now, create and initialize the thread object in your main method.
In c#, the sleep method is useful to suspend or pause the current thread execution for a specified time. We can suspend the thread execution either by passing the time in milliseconds or with TimeSpan property like as shown below. TimeSpan ts = new TimeSpan(0,0,1); Thread.
Instead of sleeping you will want to create an EventWaitHandle and use WaitOne with a timeout.
When you want the thread to wake-up early, you will simply set the event to signaled.
First create the EventWaitHandle
:
wakeUpEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
Then in your thread:
wakeUpEvent.WaitOne(new TimeSpan(1, 0, 0));
When the main program wants to wake up the thread early:
wakeUpEvent.Set();
Note: You can either set the event to auto reset or manual reset. Auto reset means once WaitOne returns from the event, it will set it back to non signaled. This is useful if you are in a loop and you signal multiple times.
A thread can be started by waiting on a WaitObject and having the other thread calling the Set method on it. Look at the WaitHandle.WaitOne method.
Here's article that may be of help as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With