Before people tell me this: I do not use Thread.sleep for anything but trying to find a way around it. I am trying to handle other people with future code that may not be .Sleep () for free. I understand very well how terrible it is for synchronizing things.
I accept a stream in a piece of my code. I want to be able to set a limit on this thread lifetime. My usual way to do this is as follows:
Thread outer = new Thread(() => { externalThread.Start(); externalThread.Join(); }); outer.Start(); outer.Join(lifetime); if (outer.ThreadState != ThreadState.Stopped) { outer.Abort(); } inner.Join();
Since then, I have discovered that I apparently cannot wake the sleeping thread before the dream ends. Worse, it still writes to the console if I give it a 10 millisecond life:
new Thread(() => { Thread.Sleep(2000); Console.WriteLine("second"); })
Although I understand .Abort () is not a hard limit on thread execution. It seems like 2 seconds would have been enough warning, but I think not ...
I tried checking the status of WaitSleepJoin and .Interrupt (); it throws a thread or throws an exception (sorry, not sure. Windows tells me that it crashed if the debugger is not working, and if it is running, it works as if the interrupt was not called) and still writes to the console through 2 seconds, .Resume () does not seem to do anything for the sleeping thread.
Is there a way to wake a thread without waiting for the end of its sleep? I understand that stopping is not “immediate”, so Console.WriteLine can be called independently; this is the second second waiting for me. What if it's a 10 day wait? Since I can’t control the flows that enter, I don’t know, and this is not a way to prevent this ...
source share