我正在尝试创建一个 Sheduler(为了好玩),但它失败了。奇怪的是,当我以步进式调试时,我的程序工作正常,但是当我删除所有断点时,它在打印最后一个值后冻结。所以问题:为什么它会冻结?第二:我正在使用Thread.Resume
and Thread.Suspend
,但它们被标记为已过时。我怎样才能避免它?
代码如下:
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication143
{
internal class Program
{
private static void Main()
{
var rrs = new RobinRoundSheduler(2, () =>
{
for (int i = 0; i < 2; i++)
{
Console.WriteLine("{0} {1}", i,
Thread.CurrentThread.ManagedThreadId);
}
}) {TimeForTask = new TimeSpan(1)};
rrs.Start();
Console.ReadKey();
}
}
internal class RobinRoundSheduler
{
private readonly LinkedList<Thread> _threads;
public TimeSpan TimeForTask { get; set; }
public RobinRoundSheduler(int taskCount, ThreadStart start)
{
TimeForTask = TimeSpan.FromSeconds(1);
_threads = new LinkedList<Thread>();
for (int i = 0; i < taskCount; i++)
{
_threads.AddLast(new Thread(start));
}
}
public void Start()
{
while (_threads.Count > 0)
{
var list = new List<Thread>();
foreach (var thread in _threads)
{
lock (thread)
{
if (thread.ThreadState == ThreadState.Unstarted)
thread.Start();
else
thread.Resume();
}
thread.Join(TimeForTask);
lock (thread)
{
if (thread.ThreadState == ThreadState.Stopped || thread.ThreadState == ThreadState.Aborted)
list.Add(thread);
else
{
thread.Suspend();
}
}
}
list.ForEach(thread => _threads.Remove(thread));
}
}
}
}
由于 Thread.Suspend() 方法似乎存在死锁问题,但我不知道在调用方法中不添加对 ManualResetEvents 的检查的情况下挂起线程的另一种选择。但我想调用方法对多线程一无所知。