我要同时取回10-20个网址的内容。。。如果要写多线程,怎么写好?
task t = new task ();
task t2=new task();
如果我有10个我不要累死了?
如果我这样写呢?
for(按网址个数循环 )
{
task t=task.factory.startnew(getweb);
}
public void getweb(){...}
那我怎么才能知道所有的线程执行结束了?
t.wait() ? 但感觉好像不对啊
?
------解决方案--------------------------------------------------------
for 循环,创建10个Thread,然后将url传入线程
------解决方案--------------------------------------------------------
http://msdn.microsoft.com/zh-cn/library/ksb7zs2x(v=vs.80).aspx
------解决方案--------------------------------------------------------
供参考
readonly object waitLock = new object();
int waitCount;
void main()
{
waitCount = 10;//任务回调次数
//异步任务,请保证onTaskFinally被回调
Monitor.Enter(waitLock);
try
{
if (waitCount != 0) Monitor.Wait(waitLock);
}
finally { Monitor.Exit(waitLock); }
}
void onTaskFinally()
{
if (Interlocked.Decrement(ref waitCount) == 0)
{
Monitor.Enter(waitLock);
try
{
Monitor.Pulse(waitLock);
}
finally { Monitor.Exit(waitLock); }
}
}
------解决方案--------------------------------------------------------
用循环啊
[align=left]for (int i = 0; i < 10; i++)
{
Thread mythread = new Thread(run);
mythread.Start();
}[/align]