我正在尝试模拟(非常基本且简单的)操作系统进程管理器子系统,我有三个“进程”(工作人员)向控制台写入内容(这是一个示例):
public class Message
{
public Message() { }
public void Show()
{
while (true)
{
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
}
每个工作线程都应该在不同的线程上运行。我现在就是这样做的:
我有一个 Process 类,它的构造函数接受 Action 委托并从中启动一个线程,暂停它.
public class Process
{
Thread thrd;
Action act;
public Process(Action act)
{
this.act = act;
thrd = new Thread(new ThreadStart(this.act));
thrd.Start();
thrd.Suspend();
}
public void Suspend()
{
thrd.Suspend();
}
public void Resume()
{
thrd.Resume();
}
}
在这种状态下,它会在我的调度程序之前等待恢复它,给它一个运行时间片,然后再次挂起它。
public void Scheduler()
{
while (true)
{
//ProcessQueue is just FIFO queue for processes
//MainQueue is FIFO queue for ProcessQueue's
ProcessQueue currentQueue = mainQueue.Dequeue();
int count = currentQueue.Count;
if (currentQueue.Count > 0)
{
while (count > 0)
{
Process currentProcess = currentQueue.GetNext();
currentProcess.Resume();
//this is the time slice given to the process
Thread.Sleep(1000);
currentProcess.Suspend();
Console.WriteLine();
currentQueue.Add(currentProcess);
count--;
}
}
mainQueue.Enqueue(currentQueue);
}
}
问题是它不能始终如一地工作。在这种状态下它甚至根本不起作用,我必须在工作人员的 Show() 方法中的 WriteLine 之前添加 Thread.Sleep() ,就像这样。
public void Show()
{
while (true)
{
Thread.Sleep(100); //Without this line code doesn't work
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
我一直在尝试使用 ManualResetEvent 而不是挂起/恢复,它可以工作,但由于该事件是共享的,依赖它的所有线程都会同时唤醒,而我只需要一次激活一个特定线程。
如果有人可以帮助我弄清楚如何正常暂停/恢复任务/线程,那就太好了。
我正在做的是尝试模拟简单的抢占式多任务处理。
谢谢。