我用线程池来测试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)为什么同样的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();
}
}
}
static方法不能使用非static成员
private Mutext mLock = null;
//in your thread function
if( mLock == null ) mLock = new Mutex();
mLock.WaitOne();
//Enter lock region
//.....mLock.ReleaseMutex();//Leave lock region