【问题标题】:Can I put limit on creation of threads in ThreadPool?我可以限制在 ThreadPool 中创建线程吗?
【发布时间】:2014-07-12 18:23:40
【问题描述】:

我正在创建一个下载图像缩略图的 Windows Phone 8 应用程序。每个缩略图都从线程池下载到一个线程上。当有很多图片(比如 100 张)时,手机性能会因为大量线程下载缩略图而降低。

有没有一种方法可以控制线程池中一次创建的线程数?

【问题讨论】:

  • 我们需要看看您是如何启动线程来回答这个问题的。 您提供此信息,我将删除反对票。
  • 确实有办法 - 只是不要创建它们!你在掌控之中,不是吗?
  • 为什么要使用线程池?您可以使用任务来执行相同的事情,而不会消耗线程池中的太多线程。
  • 这有什么帮助?每个任务使用线程池中的一个线程。
  • @MatthewWatson 好吧,不,严格来说这不是真的。

标签: c# multithreading windows-phone-8 threadpool download


【解决方案1】:

答案是否定的,你无法控制线程池中有多少线程。但是,您可以控制应用程序使用的线程数。而不是仅仅循环浏览您需要下载的图像列表,并启动任务(或者您正在执行的操作)。创建X 数量的线程或任务,等待它们完成,然后触发更多。

【讨论】:

    【解决方案2】:

    如前所述,您无法控制线程池中的线程数量,但您可以创建一个自定义TaskScheduler,它只会同时运行一定数量的任务。您可以从here 找到示例。

    【讨论】:

      【解决方案3】:

      您可以查看以下代码作为示例。在这里,我们将线程分成块,每个块将有 32 个线程。希望这会对你有所帮助。

      int noofthread = accounts.Length;
      int startindex = 0;
      int endindex = 32;
      
      /* Runs the threads in 32 item chunks */
      try
      {
          int noofchunk = (int)Math.Ceiling(((double)noofthread / 32.00));
      
          if (noofthread < endindex)
              endindex = noofthread;
          for (int chunk = 0; chunk < noofchunk; chunk++)
          {
              List<ManualResetEvent> doneEvents = new List<ManualResetEvent>();
      
              for (int i = startindex; i < endindex; i++)
              {
                  int accountID = Convert.ToInt32(accounts[i].Id, CultureInfo.InvariantCulture);
                  string accountName = Convert.ToString(accounts[i].Name, CultureInfo.CurrentCulture);
      
                  //List AccountID : AccountNames as they're running
                  AddTransactionRecord(new StackFrame(true), accountID + ":" + accountName);
      
                  //Create RunDate
                  ReportingService.Date reportDate = new ReportingService.Date();
                  reportDate.Day = _appSettings.ReportDate.Day;
                  reportDate.Month = _appSettings.ReportDate.Month;
                  reportDate.Year = _appSettings.ReportDate.Year;
      
                  // Create object of your class
                  Class c = new Class();
                  doneEvents.Add(c.DoneEvent);
                  ThreadPool.QueueUserWorkItem(c.ThreadPoolCallback, i);
              }
      
              WaitHandle.WaitAll(doneEvents.ToArray());
              startindex += 32;
              endindex += 32;
              if (endindex > noofthread)
              {
                  endindex = noofthread;
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        ThreadPool.SetMaxThreads 可以帮助你

        【讨论】:

          猜你喜欢
          • 2012-05-07
          • 1970-01-01
          • 2011-05-31
          • 1970-01-01
          • 2011-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多