6

我在 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")

我怎样才能做到这一点?

任何想法将不胜感激!

4

4 回答 4

5

您可以尝试Parallel.Foreach。每个迭代都可以并行运行。

于 2013-01-24T04:55:43.230 回答
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();
于 2013-01-24T04:57:30.653 回答
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");


如果你想使用线程来做到这一点,你可以:

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();
    }
于 2013-01-24T04:59:05.350 回答
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 中很好

于 2013-01-28T02:22:51.500 回答