我在Asp.net C#中有问题
我有以下代码: List objectList = new List();
foreach(var item in listItem)
{
object obj = getData (item);
objectList.add(obj);
}
Console.Write("Finish all");
每次`getData(item);'大火需要大约1秒;
我希望listItem
中的所有项目同时运行,然后在foreach
完成Console.write("Finish all")
后执行
我该怎么做?
任何想法都将受到赞赏!
答案 0 :(得分:5)
您可以尝试Parallel.Foreach。每次迭代可以并行运行。
答案 1 :(得分:5)
您可以使用Task
完成任务:
var tasks = listItem.Select(item => Task.Factory.StartNew(() => aaa()));
Task.WaitAll(tasks.ToArray());
Console.Write();
如果您不需要等待所有任务完成,只需跳过WaitAll
:
var tasks = listItem.Select(item => Task.Factory.StartNew(() => aaa()));
Console.Write();
对于.NET 3.5,您可以使用ThreadPool:
listItem.ForEach(item => ThreadPool.QueueUserWorkItem(state => aaa()));
Console.Write();
答案 2 :(得分:5)
using System.Threading;
using System.Threading.Tasks;
List<Task> tasks = new List<Task>();
foreach(item in listItem)
{
tasks.Add(Task.Factory.StartNew(() => aaa()));
}
// If you want the Console.Writeline to execute immediately after starting the tasks
Console.Writeline();
Task.WaitAll(tasks.ToArray());
Console.Writeline("Finised executing all tasks");
<小时/> 如果你想使用Threads来做到这一点,你可以:
List<ManualResetEvent> resetEvents = new List<ManualResetEvent>();
.
.
.
foreach(item in lisItem)
{
Thread thread = new Thread(new ParameterizedThreadStart(aaa));
ManualResetEvent resetEvent = new ManualResetEvent(false);
resetEvents.Add(resetEvent);
thread.Start(resetEvent);
}
Console.WriteLine();
WaitHandle.WaitAll(resetEvents.ToArray<WaitHandle>());
Console.WriteLine("Finised executing all threads");
}
}
.
.
.
void aaa(object data)
{
ManualResetEvent resetEvent = data as ManualResetEvent;
// completed execution
Console.WriteLine(".");
resetEvent.Set();
}
答案 3 :(得分:1)
int itemCount = ItemList.Count;
List<object> objectList = new List<object>();
ManualResetEvent[] resetEvents = new ManualResetEvent[itemCount];
for (int i = 0; i < itemCount; i++)
{
var item= ItemList[i];
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>
{
ItemCalEvent item = getData(item);
lock (objectList)
objectList.Add(item);
resetEvents[(int)index].Set();
}), i);
}
WaitHandle.WaitAll(resetEvents);
这在.net 3.5
中很好