2

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

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

4

4 回答 4

2

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

于 2013-02-07T13:55:16.530 回答
0

您可以查看以下代码作为示例。在这里,我们将线程分成块,每个块将有 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;
        }
    }
}
于 2013-03-19T19:08:38.593 回答
0

ThreadPool.SetMaxThreads can help you

于 2014-07-12T10:23:40.333 回答
0

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

于 2013-02-07T15:23:18.540 回答