EN
C#/.NET - interrupt thread
6 points
It is possible to break blocking operations (which change thread state to WaitSleepJoin) executed in some thread with Thread.Interrupt
method.
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
class Program
7
{
8
static void Main(string[] args)
9
{
10
Thread thread = new Thread(() =>
11
{
12
DateTime t1 = DateTime.Now;
13
14
try
15
{
16
Thread.Sleep(3000);
17
}
18
catch(ThreadInterruptedException)
19
{
20
TimeSpan dt = DateTime.Now - t1;
21
22
Console.WriteLine("Thread interrupted after " + dt.TotalMilliseconds + " ms.");
23
}
24
});
25
26
thread.Start();
27
Thread.Sleep(1000);
28
thread.Interrupt();
29
}
30
}
31
}
Output:
xxxxxxxxxx
1
Thread interrupted after 1003.6518 ms.
Note: One interrupt method breaks one blocked method.