我正在尝试创建一个ThreadManager
对象来处理应用程序期间创建的线程。
整个目的是在关闭主线程之前终止线程,Form
并且在关闭期间不允许创建新线程。如您所见,我在整个线程创建代码以及内部应用了锁定AllowNewThreads
。
我很确定有时会有 2 个或更多新线程在锁上等待,这不是很糟糕,但可能会导致小的延迟。是否有另一种锁定位置的替代方案以获得更好的结果,或者可能是我尚未考虑的另一种策略?
public class ThreadManager
{
#region Fields
private List<Thread> _threads;
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static object _lock;
private bool _allowNewThreads;
#endregion
#region Properties
public bool AllowNewThreads
{
get
{
return _allowNewThreads;
}
set
{
lock (_lock)
{
_allowNewThreads = value;
}
}
}
public int CountAlive
{
get
{
int count = (from t in _threads where (t.IsAlive) select t).Count();
return count;
}
}
#endregion
#region Constructors
private ThreadManager()
{
_threads = new List<Thread>();
}
public static ThreadManager Instance
{
get { return Singleton<ThreadManager>.Instance; }
}
#endregion
#region Methods
// There must always be thread body in order to create a new thread.
// Thread parameters are the objects that are needed for calculations etc inside the thread and are optional
// Start info is the thread itself parameters needed for its creation, such as the thread name, the apartment state
// and if it's background or not. That information is optional as well.
public bool TryAddThread(ParameterizedThreadStart threadBody, object threadParams, ThreadStartInfo startInfo)
{
bool success = true;
try
{
lock (_lock)
{
if (!AllowNewThreads)
{
throw new Exception("Creation of new threads is denied.");
}
Thread f = new Thread(threadBody);
if (startInfo != null)
{
f.Name = startInfo.Name;
f.SetApartmentState(startInfo.ApartmentState);
f.IsBackground = startInfo.IsBackground;
}
if (threadParams != null)
{
f.Start(threadParams);
}
else
{
f.Start();
}
_threads.Add(f);
}
}
catch (Exception ex)
{
_logger.ErrorException("AddThread", ex);
success = false;
}
return success;
}
#endregion
}