0

我正在尝试创建一个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
}
4

1 回答 1

1

正如您在评论中提到的,您将等到线程完成工作。因此,您可以使用 代替手动管理线程ThreadPool,因为它对于短期工作更有效。对于长时间运行的任务,我会使用Task可用于 .NET 3.5 的类(支持取消!)(我认为 Rx 支持它,也许还有更简单的方法)。

线程是非常重的对象,它们的管理可能会成为您应用程序的一个棘手部分。


还有一个关于锁定对象的评论(在编辑之前),您应该尝试确保整个应用程序中每个类只有一个对象可以锁定线程,否则您会遇到令人讨厌的错误。

于 2012-07-16T15:11:21.100 回答