views:

155

answers:

2

Can Thread.Abort interrupt a thread that is sleeping (using, say, Thread.Sleep(TimeSpan.FromDays(40)) ? Or will it wait until the sleep time span has expired ?

(Remarks: FromDays(40) is of course a joke. And I know Thread.Abort is not a recommended way to stop a thread, I'm working with legacy code that I don't want to refactor for now.)

A: 

You can abort the thread from another thread only. That is, you should store the Thread reference somewhere and then call .Abort from a thread other than the one which is sleeping.

Kerido
Of course. That's how it works. But will that other thread be able to interrupt a sleeping thread before the end of the sleep time span ?
Yes, of course. That's by design.
Kerido
There's nothing preventing you from calling `Thread.CurrentThread.Abort()`
Brian Rasmussen
@Brian Rasmussen: not while I'm sleeping ;-)
@fred-hh: no of course, but I read Kerido's reply as you can only abort a thread from another thread, which isn't true. It does, however, say "the thread", so I got it wrong.
Brian Rasmussen
@Brian Rasmussen: "You can abort the thread from another thread only" -- this is really wrong. It's just how I always use it.
Kerido
+2  A: 

Code is worth a thousand words:

public static void Main(string[] args)
{
    var sleepy = new Thread(() => Thread.Sleep(20000));

    sleepy.Start();
    Thread.Sleep(100);
    sleepy.Abort();
    sleepy.Join();
}

The program ends before the sleep time is exhausted.

João Angelo
I'll try that, since experience is worth a thousand Lords ;-) if it succeeds as advertised, I'll accept your answer.
But what will happen if `Sleep(TimeSpan.FromDays(40))`? Does it stop before program ends or not this is question about
zabulus
It indeed works as advertised.
@zabulus, read the remarks of the question. `TimeSpan.FromDays(40)` just illustrates that the thread will be sleeping. Oh, and by the way calling `Thread.Sleep` with `TimeSpan.FromDays(40)` will cause an `ArgumentOutOfRangeException`.
João Angelo