Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a sleeping thread in .NET

if a threadA is sleeping, how will another thread threadB call threadA to start ? Please provide an example if possible.

like image 519
SoftwareGeek Avatar asked Feb 14 '10 03:02

SoftwareGeek


People also ask

How do you put a thread to sleep?

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 .

What's thread sleep () in threading in C#?

Suspends the current thread for the specified number of milliseconds.

How do I start a thread in C#?

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.

How do you call a sleep method in C#?

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.


2 Answers

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.

like image 110
Brian R. Bondy Avatar answered Sep 20 '22 12:09

Brian R. Bondy


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.

like image 23
Otávio Décio Avatar answered Sep 21 '22 12:09

Otávio Décio