Example #1
0
        //http://dotnetstep.blogspot.com/2009/01/threadpool-wait-for-all-thread-to.html
        void ThreadFunctionImageProcess(object threadobj)
        {
            ThreadPoolObj obj = threadobj as ThreadPoolObj;

            if (obj != null)
            {
                //Console.WriteLine(obj.ObjectID.ToString());

                Console.WriteLine("{0} on thread {1}", obj.picSrcPath, Thread.CurrentThread.ManagedThreadId);
                ResizeImagesTask(obj.picSrcPath, obj.picDestPath, obj.picScale);

                obj.signal.Set();
            }
        }
Example #2
0
        /// <summary>
        /// 進行圖片的縮放作業
        /// </summary>
        /// <param name="sourcePath">圖片來源目錄路徑</param>
        /// <param name="destPath">產生圖片目的目錄路徑</param>
        /// <param name="scale">縮放比例</param>
        public void ResizeImages(string sourcePath, string destPath, double scale)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            var allFiles = FindImages(sourcePath);

            List <ManualResetEvent> events = new List <ManualResetEvent>();

            int fileCounter = 0;

            foreach (var filePath in allFiles)
            {
                fileCounter++;

                //寫法一:等待全部Thread 都已經 Complete
                //參考 http://dotnetstep.blogspot.com/2009/01/threadpool-wait-for-all-thread-to.html
                ThreadPoolObj tpobj = new ThreadPoolObj();
                tpobj.ObjectID    = fileCounter;
                tpobj.signal      = new ManualResetEvent(false);
                tpobj.picSrcPath  = filePath;
                tpobj.picDestPath = destPath;
                tpobj.picScale    = scale;
                events.Add(tpobj.signal);
                WaitCallback callback = new WaitCallback(ThreadFunctionImageProcess);
                ThreadPool.SetMinThreads(4, 4);
                ThreadPool.SetMaxThreads(12, 12);
                ThreadPool.QueueUserWorkItem(callback, tpobj);


                //寫法=二:
                //ThreadPool.QueueUserWorkItem((state) =>
                //{
                //    Console.WriteLine("{0} on thread {1}", filePath, Thread.CurrentThread.ManagedThreadId);
                //    ResizeImagesTask(filePath, destPath, scale);
                //});
            }

            WaitForAll(events.ToArray());

            sw.Stop();

            Console.WriteLine("本次產檔數量" + fileCounter);
            Console.WriteLine($"花費時間: {sw.ElapsedMilliseconds} ms");
        }