Using AsParallel

本文关键字:AsParallel Using | 更新日期: 2023-09-27 18:25:54

我有一个EmpId列表。我需要对这个列表上的每个EmpId执行一些操作。

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

我可以使用AsParallel执行此操作吗?基本上,我想并行处理每个员工Id。

Using AsParallel

您可能想要Parallel.ForEach:而不是AsParallel

Parallel.ForEach(ids, ProcessEmp);

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

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

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

这是的示例

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