Mubin
Mubin

Reputation: 15

Thread Sleep by name or some any other method

is there anyway to sleep the some particularthread by name or some any other source in case I've two threads

            Thread call = new Thread(() => open_page(txtbx_1.Text));
            call.Start();

            Thread call_2nd = new Thread(() => open_page(txtbx_1.Text));
            call_2nd.Start();

I want to sleep call and call_2nd for at least 15 minutes(but don't want to sleep the main Thread.

Thanks

Upvotes: 0

Views: 167

Answers (3)

JensG
JensG

Reputation: 13421

Yes, but in a different way than you might think.

Have the target thread(s) you want to sleep regularly check an manual-reset event. That event (flag) is cleared by the controlling thread whenever the target thread is supposed to sleep, otherwise it is always set. If you want the target thread(s) to sleep only for a certain amount of time, use that value as the wait timeout.

  • if the event is set (no sleep), the wait is satisfied immediately and execution continues
  • if the event is cleared (sleep), the target thread(s) stops until
    • the timeout (15 minutes = 15 * 60 * 1000 ms) elapsed
    • or the controlling thread sets the event again within that time frame

If you need to check whether or not the target thread(s) is in the waiting state, consider another event/flag/counter, set by the target thread(s), and read by the controlling thread.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182865

Why would you want a thread to sleep unless it was otherwise going to do something you didn't want it to do? And why would you ever code a thread to do something you didn't want to do?

If you're asking this question, something is very wrong somewhere in your design or implementation.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

No - you can't ask another thread to sleep. Apart from anything else, at the time when you want it to sleep it may hold a lock or other resource which really shouldn't be held while sleeping.

You'd have to do this cooperatively, with some sort of shared data between the threads indicating what you want to sleep and for how long. Alternatively, schedule a timer to only start the relevant activity after a certain length of time.

Upvotes: 3

Related Questions