您的位置:首页 > 编程语言

.NET 4中并行编程的简单例子

2010-04-16 07:09 519 查看
该文可参考http://msdn.microsoft.com/en-us/library/dd460720(VS.100).aspx

namespaceForEachDemo
{
usingSystem;
usingSystem.Drawing;//requiressystem.Drawing.dll
usingSystem.IO;
usingSystem.Threading;
usingSystem.Threading.Tasks;

classSimpleForEach
{
staticvoidMain()
{
//Asimplesourcefordemonstrationpurposes.Modifythispathasnecessary.
string[]files=System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\SamplePictures","*.jpg");
stringnewDir=@"C:\Users\Public\Pictures\SamplePictures\Modified";
System.IO.Directory.CreateDirectory(newDir);

//Methodsignature:Parallel.ForEach(IEnumerable<TSource>source,Action<TSource>body)
Parallel.ForEach(files,currentFile=>
{
//Themorecomputationalworkyoudohere,thegreater
//thespeedupcomparedtoasequentialforeachloop.
stringfilename=System.IO.Path.GetFileName(currentFile);
System.Drawing.Bitmapbitmap=newSystem.Drawing.Bitmap(currentFile);

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

//Peekbehindthescenestoseehowworkisparallelized.
//Butbeaware:ThreadcontentionfortheConsoleslowsdownparallelloops!!!
Console.WriteLine("Processing{0}onthread{1}",filename,
Thread.CurrentThread.ManagedThreadId);

}//closelambdaexpression
);//closemethodinvocation

//Keeptheconsolewindowopenindebugmode.
Console.WriteLine("Processingcomplete.Pressanykeytoexit.");
Console.ReadKey();
}
}
}

注意:
并行编程与之前的多线程的区别,并行编程其实可以理解为多核编程,它可以更好地利用多CPU的优势。而之前的多线程其实是需要切换线程的。

.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: