C# ThreadPool学习
例子1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
namespace checkurl
{
class Program
{
static void Main(string[] args)
{
//定义一个 WaitCallback 委托的对象,将它作为参数传递给ThreadPool.QueueUserWorkItem ()方法
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadWork),"第一个线程池");
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadWork), "第二个线程池");
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadWork), "第三个线程池");
Console.ReadLine();
}
//向线程传递参数
public static void MyThreadWork(object state)
{
Console.WriteLine("线程现在开始启动…… {0}",state.ToString());
Thread.Sleep(10000);
Console.WriteLine("运行结束…… {0}", state.ToString());
}
}
运行结果:
ManualResetEvent允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。
Reset(): 当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时, 它调用 Reset 以将 ManualResetEvent 置于非终止状态。此线程可被视为控制 ManualResetEvent。
为了把状态修改为无信号的,必须调用ReSet()方法。
WaitOne(): 调用ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。
Set ()当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。Set将事件状态设置为终止状态,允许一个或多个等待线程继续。
为了把状态修改为有信号的,必须调用Set()方法。
ManualResetEvent对象只能拥有两种状态之一:有信号(True)或无信号(false)。ManualResetEvent类继承于WaitHandle类,其构造函数的参数可确定对象的初始状态。
例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
namespace checkurl
{
class Program
{
static String[] url = new String[2]{ "http://www.baidu.com/","http://www.google.com.hk/" };
static int completeProxyCount; public static ManualResetEvent clientsCompletedEvent = new ManualResetEvent(false); static void Main(string[] args)
{
for (int i = 0; i < url.Length; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadWork), i); }
try { clientsCompletedEvent.WaitOne(); } finally { clientsCompletedEvent.Close(); } System.Console.ReadLine(); } public static void MyThreadWork(object state) { urlcheck(Convert.ToInt32(state)); } static void urlcheck(int i) //web request
{
System.Net.ServicePointManager.DefaultConnectionLimit = 1000; try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url[i]);
//request.Proxy = new WebProxy("10.60.0.XX");
//request.CookieContainer = container;
request.Method = "GET";
request.KeepAlive = false;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.2; .NET CLR 3.5.21022; CIBA)";
request.Timeout = 10000;
WebResponse response = request.GetResponse();
if (response.ResponseUri.ToString() == url[i])
{
System.Console.WriteLine("第{0}个url请求成功,response的url是:{1}", i, response.ResponseUri.ToString());
}
else
{
System.Console.WriteLine("第{0}个url请求失败,response的url是:{1}", i, response.ResponseUri.ToString());
}
}
catch (Exception ex)
{
System.Console.WriteLine("第" + i + "个url" + ex.Message);
}
finally
{
if (Interlocked.Increment(ref completeProxyCount) == url.Length) { clientsCompletedEvent.Set(); } }
}
}
}