希望懂c#多线程的兄弟帮忙看看我想下载一个网页链接里面的所有图片,并在限制线程运行数量的情况下,使用多线程对图片进行下载和保存。我提取出了一个方法 
public static void PhotoSave(object str)其中str中包含了图片的路径
我想用多线程控制PhotoSave运行我的做法是下面这样的:
for
{
   Thread thr = new Thread(new ParameterizedThreadStart(PhotoSave));
   thr.Start(param);
}
在PhotoSave中使用Mutex控制实际运行的线程的数量。运行结果:
1,我这样做之后运行之后提示虚拟内存不足。问题:
1,如何解释并解决这个问题?
2,请问一下线程在一开始new的时候即使它没有开始运行就分配资源吗?

解决方案 »

  1.   

    死循环,不断分配内存当然虚拟内存不足。
    thr.Start(param); 主线程是不会挂起的还会继续运行。
      

  2.   

    不是死循环,我只是为了想说明问题就在那放了一个for
    我看了你们的回帖,你们的意思是说假如要限制线程的数量的话就必须在创建的时候进行限制?
      

  3.   

    后来在网上又看了很多,完成了下面的代码,很简陋,但是实现我的目的。using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    using System.Runtime.InteropServices;namespace ConsoleApplication6
    {
        public class MutexTest
        {
            private static int poolFlag = 0;//标记
            private const int amountThread = 100;//线程总量
            private const int maxThread = 3;//可执行线程最大数量
            private static Mutex muxConsole = new Mutex();        public static void Main()
            {
                for (int i = 0; i < 100; i++)
                {
                    while (true)
                    {
                        if (poolFlag < 3)
                        {
                            //Thread trd = new Thread(new ThreadStart(Run));
                            //ThreadPool.
                            //ThreadPool.QueueUserWorkItem(new WaitCallback(Run));
                            Thread trd = new Thread(new ThreadStart(Run));
                            trd.Start();
                            trd.Name = "线程" + i.ToString();
                            break;
                        }
                        Thread.Sleep(10);
                    }
                }
                Console.Read();        }        public static void Run()
            {
                Interlocked.Increment(ref poolFlag); //标记+1
                Console.WriteLine("{0} 正在运行......\n", Thread.CurrentThread.Name);
                IntPtr vBuffer = Marshal.AllocHGlobal(102400);
                Thread.Sleep(3000); //模拟执行
                
                //Console.WriteLine("{0} 已经中止......\n", Thread.CurrentThread.Name);
                
                Interlocked.Decrement(ref poolFlag);
            }
        }}