我用线程池来测试URL是否通,为什么结果不正确,请问
(1)为什么同样的URL,有时请求有回应,有时会出错,什么原因?
(2)怎么控制线程池中线程的数量,超过了一定的值就会报没有自由线程可用,怎么解决?(注:不想修改CorSetMaxThreads的值)
(3)如果不用线程池,请问用线程怎么控制谢谢各位!代码如下:using System;
using System.Net;
using System.Threading;namespace ThreadPoolDemoConsole
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
        private static string[] str ={"http://www.sina.com.cn","http://www.163.net","http://www.sohu.com"};//URL随便
private static void test(object obj)
{
string s="";
lock(str)//这个地方我用LOCK(THIS)不知道为什么老报错:(
{
try
{
// Create a new WebRequest Object to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create((string)obj);
// Set the 'Timeout' property in Milliseconds.
myWebRequest.Timeout=2000; WebResponse myWebResponse=myWebRequest.GetResponse(); s = s+" "+(string)obj+" "+myWebResponse.ResponseUri.ToString();
Console.WriteLine(s);

}
catch(Exception ex)
{
s = s+" "+(string)obj+" "+"erro";
Console.WriteLine(s);
}
} }
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
for(int i=0;i<13;i++)
{
int k = i%3;                                  //为了有多个URL,为了方便,使用重复的URL

ThreadPool.QueueUserWorkItem(new WaitCallback(test),str[k]);
}
Console.ReadLine();
}
}
}

解决方案 »

  1.   

    lock(str)//这个地方我用LOCK(THIS)不知道为什么老报错:(
    static方法不能使用非static成员
      

  2.   

    帮你顶,第二个问题我也想知道,我想可不可以在回调函数最后那里执行一下WaitHandle.WaitAny(IManualResetEvent);如果真就执行一个函数把一个新线程放进去。
      

  3.   

    lock部分用mutex来替换,例如:
    private Mutext mLock = null;
    //in your thread function
    if( mLock == null ) mLock = new Mutex();
    mLock.WaitOne();
    //Enter lock region
    //.....mLock.ReleaseMutex();//Leave lock region