Skip to content

Instantly share code, notes, and snippets.

@Sheeo
Created March 21, 2012 23:23
Show Gist options
  • Save Sheeo/2154103 to your computer and use it in GitHub Desktop.
Save Sheeo/2154103 to your computer and use it in GitHub Desktop.
using System;
using System.Security.Permissions;
using System.Threading;
class ThreadInterrupt
{
static void Main()
{
StayAwake stayAwake = new StayAwake();
Thread newThread =
new Thread(new ThreadStart(stayAwake.ThreadMethod));
newThread.Start();
Thread.Sleep(500);
stayAwake.SleepSwitch = true;
Thread.Sleep(500);
newThread.Interrupt();
Console.WriteLine("Main thread calls Interrupt on newThread.");
// Tell newThread to go to sleep.
stayAwake.SleepSwitch = true;
Console.ReadLine();
Console.WriteLine("Main thread sending int");
newThread.Interrupt();
Console.Write(newThread.ThreadState);
stayAwake.SleepSwitch = true;
Console.ReadLine();
}
}
class StayAwake
{
bool sleepSwitch = false;
public bool SleepSwitch
{
set{ sleepSwitch = value; }
}
public StayAwake(){}
public void ThreadMethod()
{
Console.WriteLine("newThread is executing ThreadMethod.");
while(!sleepSwitch)
{
// Use SpinWait instead of Sleep to demonstrate the
// effect of calling Interrupt on a running thread.
Thread.SpinWait(10000000);
}
try
{
Console.WriteLine("newThread going to sleep.");
// When newThread goes to sleep, it is immediately
// woken up by a ThreadInterruptedException.
Thread.Sleep(Timeout.Infinite);
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("Thread woke up!");
sleepSwitch = false;
ThreadMethod();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment