【问题标题】:Dont work garbege collector with ThreadPool.QueueUserWorkItem(不要使用 ThreadPool.QueueUserWorkItem(
【发布时间】:2022-06-10 21:11:40
【问题描述】:

我有一个带有 SortedList 的课程。 SortedList 填充在类构造函数中。我在一个方法中使用这个类,在该方法中我创建了一个类的实例并将其放入 ThreadPool.QueueUserWorkItem。 当 ThreadPool 完成并退出此方法时,我尝试再次调用此方法,它给出错误“有一个带有此键的 SortedList 项”。在此类中使用 IDisposable 并没有帮助。我错过了什么?

    //method with ThreadPool
    static void Time()
    {
        ConsoleTime consoleTime = new ConsoleTime();
        consoleTime.PreOutput();
        
        bool showTime = true;
        ThreadPool.QueueUserWorkItem(
            callback =>
            {
                while (showTime)
                {
                    consoleTime.UpTime();
                    Thread.Sleep(10);
                }
            });
        
        Console.ReadKey();
        showTime = false;
        Thread.Sleep(10);

        Menu();

    }

/////////////////////////////////////// /////

//Class 
public class ConsoleTime
{
    //private static readonly string[,] charList = new string[12, 5];
    private static readonly SortedList<string, string[]> charList = new SortedList<string, string[]>();
   
    public ConsoleTime()
    {
        string[] charMass = new string[5];
        
        charMass[0] = "█████";
        charMass[1] = "█   █";
        charMass[2] = "█   █";
        charMass[3] = "█   █";
        charMass[4] = "█████";

        //THIS IS ERROR STRING{
        charList.Add("0", (string[])charMass.Clone());
        //}

        charMass[0] = "  ██ ";
        charMass[1] = " ███ ";
        charMass[2] = "█ ██ ";
        charMass[3] = "  ██ ";
        charMass[4] = "█████";
        charList.Add("1", (string[])charMass.Clone());

    }

    //update time on screen
    public void UpTime()
    {
        DateTime thisMoment = DateTime.Now;

        string[] output = new string[5];
        output = GetStrTime(thisMoment);
        
        for (int i = 0; i < 5; i++)
        {
            Console.CursorVisible = false;
            Console.SetCursorPosition(5, i+3);
            Console.Write(output[i]);
        }
        

    }

【问题讨论】:

  • 你为什么不使用计时器和/或任务?问题不在于垃圾回收,代码正在冻结线程池线程
  • 问题是......它是静态的 - 这显然意味着它没有与所有者类的任何实例相关
  • 您有一个 static 成员,您正在使用实例构造函数进行初始化。这似乎不对。

标签: c# threadpool


猜你喜欢
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2011-09-05
  • 2011-03-04
相关资源
最近更新 更多