private static DelgFunc fc ; static int ThreadFunction(int i) { Thread.Sleep(i); return i; } /// <summary> /// The main entry point for the application. /// </summary>
static void Main(string[] args) {
fc = new DelgFunc(ThreadFunction); int threads=10; ArrayList isr = new ArrayList(); ArrayList wh= new ArrayList(); for(int i=0;i<threads;i++) { Random rdm = new Random(i); IAsyncResult ias=fc.BeginInvoke(rdm.Next(2000,5000),new System.AsyncCallback(ThreadResult),null); isr.Add( ias ); wh.Add( ias.AsyncWaitHandle ); } WaitHandle[] wharry = (WaitHandle[]) wh.ToArray(typeof(WaitHandle));
ar.AsyncWaitHandle.WaitAny
{
Thread.Sleep(i);
return i;
}static void Main()
{
DelgFunc fc = new DelgFunc(ThreadFunction);
int threads=10;
ArrayList isr = new ArrayList();
ArrayList wh= new ArrayList();
for(int i=0;i<threads;i++)
{
Random rdm = new Random(i);
IAsyncResult ias=fc.BeginInvoke(rdm.Next(2000,5000),null,null);
isr.Add( ias );
wh.Add( ias.AsyncWaitHandle );
}
for(int i=0;i<threads;i++)
{
WaitHandle[] wharry = (WaitHandle[]) wh.ToArray(typeof(WaitHandle));
int nh=WaitHandle.WaitAny(wharry);
Console.WriteLine(fc.EndInvoke((IAsyncResult)isr[nh]));
isr.RemoveAt(nh);
wh.RemoveAt(nh);
}
Console.ReadLine();
}
这样处理很麻烦的,有没有比较省事的方法?谢谢。
static int ThreadFunction(int i)
{
Thread.Sleep(i);
return i;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
fc = new DelgFunc(ThreadFunction);
int threads=10;
ArrayList isr = new ArrayList();
ArrayList wh= new ArrayList();
for(int i=0;i<threads;i++)
{
Random rdm = new Random(i);
IAsyncResult ias=fc.BeginInvoke(rdm.Next(2000,5000),new System.AsyncCallback(ThreadResult),null);
isr.Add( ias );
wh.Add( ias.AsyncWaitHandle );
}
WaitHandle[] wharry = (WaitHandle[]) wh.ToArray(typeof(WaitHandle));
Console.ReadLine(); }
protected static void ThreadResult(IAsyncResult ar)
{
if(ar.IsCompleted)
{
int ddd = (int) fc.EndInvoke(ar);
Console.WriteLine(ddd);
}
}
Console.ReadLine();
中间少了一句话:
WaitHandle.WaitAll(wharry);这样主线程在所有线程没有结束前阻塞了,而且每个线程处理完后通过ThreadResult代理来处理结果。
{
调用BeginInvoke启动最多5个线程调用WaitHandle.WaitAny等待上述任一个线程结束}while(100个线程未全部执行完毕)为了实现上面的要求,如何优化代码?另:To ThreadSharp(ThreadSharp V2006) 我必须要使用BeginInvoke来启动线程,所以Thread无法满足我的要求.另外Join方法无法等待多个线程中的任一线程结束(处于有信号状态)这一点.
用。NET自带的ThreadPool
或者
http://www.codeproject.com/csharp/smartthreadpool.aspSmart Thread Pool这个池,里面有很多好的功能,比自带的那个强大多了如果你是研究线程的话,把它的源代码看懂。应该会有收获的。