C#Thread的Interrupt方法
2016-06-02 15:10
489 查看
Interrupt方法,只可以中断处于WaitSleepJoin状态的线程,当线程不为WaitSleepJoin时,线程将恢复执行。
调用Interrupt方法会产生ThreadInterruptException异常
class Program
{
static void Main(string[] args)
{
StayAwake stayAwake = new StayAwake();
Thread newThread = new Thread(new ThreadStart(stayAwake.ThreadMethod));
newThread.Start();
newThread.Name = "new thread";
newThread.Interrupt();
Console.WriteLine("main thread calls interrupt on new thread");
stayAwake.SleepSwitch = true;
Console.WriteLine("1stat " + Thread.CurrentThread.ThreadState);
newThread.Join();
}
}
class StayAwake
{
bool sleepSwitch = false;
public bool SleepSwitch
{
set
{
sleepSwitch = value;
}
}
public void ThreadMethod()
{
Console.WriteLine("new thread is executing thread method");
while (!sleepSwitch)
{
Thread.SpinWait(10000000);
}
try
{
Console.WriteLine("2name " + Thread.CurrentThread.Name);
Console.WriteLine("2stat " + Thread.CurrentThread.ThreadState);
Console.WriteLine("new thread going to sleep");
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("new thread can not go to sleep -" + "interrupted by main thread");
}
}
}
调用Interrupt方法会产生ThreadInterruptException异常
class Program
{
static void Main(string[] args)
{
StayAwake stayAwake = new StayAwake();
Thread newThread = new Thread(new ThreadStart(stayAwake.ThreadMethod));
newThread.Start();
newThread.Name = "new thread";
newThread.Interrupt();
Console.WriteLine("main thread calls interrupt on new thread");
stayAwake.SleepSwitch = true;
Console.WriteLine("1stat " + Thread.CurrentThread.ThreadState);
newThread.Join();
}
}
class StayAwake
{
bool sleepSwitch = false;
public bool SleepSwitch
{
set
{
sleepSwitch = value;
}
}
public void ThreadMethod()
{
Console.WriteLine("new thread is executing thread method");
while (!sleepSwitch)
{
Thread.SpinWait(10000000);
}
try
{
Console.WriteLine("2name " + Thread.CurrentThread.Name);
Console.WriteLine("2stat " + Thread.CurrentThread.ThreadState);
Console.WriteLine("new thread going to sleep");
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("new thread can not go to sleep -" + "interrupted by main thread");
}
}
}
相关文章推荐
- C#通过安全证书生成签名和验签辅助类
- C# RSA 算法
- c# Dictionary求交集、差集、并集
- C#Thread的Join方法
- C#操作XML之——读取XML节点
- C#中可以用XmlDocument类操作Xml文件
- 简介C#读取XML的两种方式
- C#多线程Thread.Abort的使用
- c# 可空类型
- C#实现两个时间相减的方法
- C#中重写(override)和覆盖(new)的区别 (备注:转,留自己用)
- C# 拼接字符串
- C# in depth学习(1)
- C#多态
- C#—实验9.6和9.7
- C#进阶系列——WebApi 路由机制剖析:你准备好了吗?
- C#—容器类控件操作
- C#外部类、内部类(嵌套类)之间的成员访问特点
- c# 三种传参方式 in,out,ref
- 反反外挂驱动的驱动