使用AsParallel

时间:2012-02-24 17:36:51

标签: c#

我有一份EmpIds列表。我需要在此列表中为每个EmpId执行一些操作。

void ProcessEmp(EmpId empId)
{
  // process the emp
} 

我可以使用AsParallel执行此操作,而不是一次循环遍历每个员工ID吗?基本上我想平行处理每个emp Id。

3 个答案:

答案 0 :(得分:5)

而不是AsParallel,您可能需要Parallel.ForEach

Parallel.ForEach(ids, ProcessEmp);

或者,如果您不喜欢方法组转换:

Parallel.ForEach(ids, id =>
{
    Console.WriteLine("Processing {0}", id);
    ProcessEmp(id);
});

答案 1 :(得分:2)

您可以使用Parallel.Foreach()http://msdn.microsoft.com/en-us/library/dd537608.aspx

答案 2 :(得分:0)

以下是示例示例

string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
string newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";
System.IO.Directory.CreateDirectory(newDir);

//  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
Parallel.ForEach(files, currentFile =>
{
    // The more computational work you do here, the greater 
    // the speedup compared to a sequential foreach loop.
    string filename = System.IO.Path.GetFileName(currentFile);
    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);

    bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    bitmap.Save(System.IO.Path.Combine(newDir, filename));

    // Peek behind the scenes to see how work is parallelized.
    // But be aware: Thread contention for the Console slows down parallel loops!!!
    Console.WriteLine("Processing {0} on thread {1}", filename,
    Thread.CurrentThread.ManagedThreadId);

    } //close lambda expression
); //close method invocation
相关问题