Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I wake a sleeping thread in C#?
    primarykey
    data
    text
    <p>Before people suggest it: <strong>I am not using Thread.sleep for <em>anything</em></strong> except trying to find a way to work around it. I am trying to handle other people's future code which may not be .Sleep() free. I have a very good grasp of how horrible it is for synchronizing things.</p> <p>I accept a thread in a chunk of my code. I wish to be able to set a limit to this thread's lifetime. My usual method of doing so goes like this:</p> <pre><code>Thread outer = new Thread(() =&gt; { externalThread.Start(); externalThread.Join(); }); outer.Start(); outer.Join(lifetime); if (outer.ThreadState != ThreadState.Stopped) { outer.Abort(); } inner.Join(); </code></pre> <p>I've since discovered that I apparently cannot wake a sleeping thread before the sleep finishes. To make matters worse, this still writes to the console if I give it a lifetime of 10 milliseconds:</p> <pre><code>new Thread(() =&gt; { Thread.Sleep(2000); Console.WriteLine("second"); }) </code></pre> <p>Though I realize .Abort() isn't a hard-limit on thread execution. It seems 2 seconds would be enough of a warning, but I guess not...</p> <p>I've tried checking for WaitSleepJoin status, and .Interrupt(); it crashes the thread, or throws an exception (sorry, unsure which. Windows tells me it crashed if no debugger's running, and if it is running it runs as if interrupt wasn't called), and still writes to the console after 2 seconds. .Resume() apparently does nothing to a sleeping thread.</p> <p><em>Is</em> there a way to wake a thread, without waiting for its Sleep to expire? I understand that stopping isn't "immediate", so that Console.WriteLine may be called regardless; it's the 2 second wait that's bugging me. What if it's a 10 day wait? Since I can't control the threads that come in, I have no way of knowing, and it seems no way of <em>preventing</em> such a thing...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload