110,533
社区成员
发帖
与我相关
我的任务
分享
public class ThreadsTest : IDisposable
{
public ThreadsTest()
{
this.threads = new List<Thread>();
this.Initialized = false;
this.Disposing = false;
this.blocker = new AutoResetEvent(false);
int processerCount = Environment.ProcessorCount > 0 ?
Environment.ProcessorCount : 1;
for (int i = 0; i < processerCount; i++)
{
Thread thread = new Thread(this.ThreadFunc);
thread.Name = string.Format("Threads test worker thread {0}", i);
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
thread.Start();
this.threads.Add(thread);
}
this.Initialized = true;
this.blocker.Set();
}
public bool Initialized { get; private set; }
public bool Disposing { get; private set; }
private List<Thread> threads;
private AutoResetEvent blocker;
public event Action Disposed;
private void ThreadFunc()
{
if (!this.Initialized)
{
this.blocker.WaitOne();
}
while (true)
{
if (this.Disposing)
{
break;
}
Console.WriteLine("{0} running.", Thread.CurrentThread.Name);
this.blocker.WaitOne();
}
if (this.Disposed != null)
{
this.Disposed();
}
}
public void Dispose()
{
this.Disposing = true;
this.blocker.Set();
}
}
public class ThreadsTestClass
{
private ThreadsTest test;
public void Do()
{
this.test = new ThreadsTest();
this.test.Disposed += this.ThreadsDisposed;
Task.Factory.StartNew(this.TestMethod).Wait();
Console.WriteLine("Test Completed.");
}
private void TestMethod()
{
Console.WriteLine("Press enter to finish");
Console.ReadLine();
this.test.Dispose();
}
private void ThreadsDisposed()
{
this.test.Disposed -= this.ThreadsDisposed;
foreach (var thread in this.test.Threads)
{
Console.WriteLine("{0} alive: {1}", thread.Name, thread.IsAlive);
}
this.test = null;
}
}