📄 threadpool.cs
字号:
namespace NCindy.Threading
{
using NCindy.Util.Logging;
using System;
using System.Collections.Generic;
using System.Security;
using System.Threading;
public class ThreadPool
{
private static int _threadsPerCpu = 1;
private int cachedWorkerListCount;
private static readonly ILogger log = LogFactory.CreateLogger(MethodBase.GetCurrentMethod().ReflectedType);
private string name;
private static readonly int NumberOfProcessors = GetNumberOfProcessors();
internal int pendingTaskCount;
private ManualResetEvent startupCompleteEvent;
internal readonly List<TaskQueue> taskQueueList = new List<TaskQueue>();
private bool useBackgroundThreads;
internal readonly List<TaskExecutionWorker> workerList = new List<TaskExecutionWorker>();
public ThreadPool(int threadCount, ThreadPriority priority, bool useBackgroundThreads, string threadPoolName)
{
if (threadCount == 0)
{
threadCount = Math.Max(NumberOfProcessors, 2) * ThreadsPerCpu;
}
else if (threadCount < 0)
{
throw new ArgumentException("Cannot create a negative number of threads. Pass 0 to use default.", "threadCount");
}
if (threadPoolName == null)
{
this.name = string.Empty;
}
else
{
this.name = threadPoolName;
}
this.useBackgroundThreads = useBackgroundThreads;
for (int i = 0; i < threadCount; i++)
{
this.AddWorker(priority);
}
this.StartWorkers();
}
public void AddBlockTask(ITask task)
{
}
public void AddNonBlockTask(ITask task)
{
}
private void AddWorker(ThreadPriority priority)
{
TaskExecutionWorker worker = new TaskExecutionWorker(this);
Thread thread = new Thread(new ThreadStart(worker.ExecutionLoop));
thread.Name = this.name;
thread.Priority = priority;
thread.IsBackground = this.useBackgroundThreads;
worker.thread = thread;
this.workerList.Add(worker);
this.cachedWorkerListCount++;
}
private static int GetNumberOfProcessors()
{
try
{
return Environment.get_ProcessorCount();
}
catch (SecurityException)
{
return 1;
}
}
private void StartWorkers()
{
try
{
List<TaskExecutionWorker>.Enumerator enumerator = this.workerList.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
TaskExecutionWorker worker = enumerator.get_Current();
try
{
worker.thread.Start();
continue;
}
catch (Exception exception)
{
if (log.IsWarnEnabled)
{
log.Warn("Work thread start failed.", exception);
}
continue;
}
}
}
finally
{
enumerator.Dispose();
}
}
finally
{
this.startupCompleteEvent.WaitOne();
this.startupCompleteEvent.Close();
this.startupCompleteEvent = null;
}
}
public static int ThreadsPerCpu
{
get
{
return _threadsPerCpu;
}
set
{
_threadsPerCpu = value;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -