我正在尝试创建一个Sheduler(为了好玩),但它失败了。奇怪的是,当我在步进式调试时,我的程序运行正常,但是当我删除所有断点时,它会在打印完最后一个值后冻结。所以问题:为什么会冻结?第二:我正在使用Thread.Resume
和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的检查。但我想调用方法对多线程一无所知。