i'm trying to demonstrate timeslicing among equal high priority threads without putting threads to sleep. to do this i'm trying to run a timer while executing a very long loop sequence in order to get the processor to round-robin through the high priority threads. here's what i have:
static void Main(string[] args)
{
System.Timers.Timer aTimer = new System.Timers.Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent)
// Set the Interval to 5 seconds (5000 milliseconds).
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine( "\n \nThis demonstrates time-slicing among high priority threads.\nThe processor alternates between the two high priority threads first before letting the low priority thread run.\n \n");
//class time slice object
imeSlice sliceTS = new TimeSlice();
//high priority thread #1
Thread threadHighSlice1 = new Thread(new ThreadStart(sliceTS.Print));
threadHighSlice1.Priority = ThreadPriority.Highest;
threadHighSlice1.Name = "1";
threadHighSlice1.Start();
//high priority thread #2
Thread threadHighSlice2 = new Thread(new ThreadStart(sliceTS.Print));
threadHighSlice2.Priority = ThreadPriority.Highest;
threadHighSlice2.Name = "2";
threadHighSlice2.Start();
//high priority thread #2
Thread threadHighSlice3 = new Thread(new ThreadStart(sliceTS.Print));
threadHighSlice3.Priority = ThreadPriority.Highest;
threadHighSlice3.Name = "3";
threadHighSlice3.Start();
//low priority thread
Thread threadLowSlice = new Thread(new ThreadStart(sliceTS.Print));
threadLowSlice.Priority = ThreadPriority.Lowest;
threadLowSlice.Name = "Low";
threadLowSlice.Start();
// Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object aTimer, ElapsedEventArgs e)
{
Thread current = Thread.CurrentThread;
MessageBox.Show(current.Name);
}
}
class TimeSlice : EventArgs
{
public void Print()
{
Thread current = Thread.CurrentThread;
int number = 0;
int num = 0;
while(num < 100000)
{
Console.Write(current.Name);
num = num + 1;
}
}
i'm trying to get the timer elapsed event to print the thread currently being executed in a message box. but i can't seem to figure out how to pass the value. is there an easier way to accomplish what i'm trying to do?