Visual Studio 2015单例问题

时间:2017-01-20 15:27:05

标签: c#

我在VS2015中创建了ClassLibrary项目。 我在里面创建了Singleton类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Library
{
    public class PoolOfThreads
    {
        private static PoolOfThreads instance = new PoolOfThreads();

        public static PoolOfThreads Instance
        {
            get { return instance; }
        }

        private List<Thread> listOfThreads;
        private int maxThreads;

        public int MaxThreads
        {
            get { return maxThreads; }
            set { maxThreads = value; }
        }

        private PoolOfThreads()
        {
            listOfThreads = new List<Thread>();
        }


        /// <exception cref="Exception"></exception>
        public Thread NewThread(ParameterizedThreadStart threadMethod)
        {
            FreeThreads();

            if (listOfThreads.Count < maxThreads)
            {
                Thread thread = new Thread(threadMethod);
                listOfThreads.Add(thread);
                return thread;
            }
            else
                throw new Exception("No free threads...");
        }

        private void FreeThreads()
        {
            /*var freeThreads = listOfThreads.Select(thread => thread.ThreadState == ThreadState.Stopped) as List<Thread>;
            foreach (Thread thread in freeThreads)
                listOfThreads.Remove(thread);
            */
            listOfThreads.RemoveAll(thread => thread.ThreadState == ThreadState.Stopped || thread.ThreadState == ThreadState.Aborted);
        }
    }
}

我还创建了UnitTest项目。 我添加了对库的引用,一切正常。 我可以测试我的单身人士。

问题在于我创建Windows Form Appl。 每个项目都在同一个解决方案中。我添加了参考文献。

    using Library;
    using System.Net;
    using CalkaRozproszona.Classes;

    namespace CalkaRozproszona
    {
        public partial class ServerApplication : Form
        {
            Server server;
            ListObservator listObservator;
            PoolOfThreads.Instance.MaxThreads = 10;
            //Library.PoolOfThreads.Instance.MaxThreads = 10;


            public ServerApplication()
            {
                InitializeComponent();
            }
        }
     }

我无法访问我的单一类PoolOfThreads。 enter image description here。 正如你所看到的,VS看到了这门课。 但是当我尝试进入Instance属性时,我收到错误: enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:-2)

您可以将其分配给这样的变量:

public partial class ServerApplication : Form
{
    Library.PoolOfThreads poolOfThreads = Library.PoolOfThreads.Instance;