我有一个程序,使用户int输入“ 1”并根据目录中的文件数量将其递增,然后在每个文件上标记int(首先为1,以此类推,1 ++)。每个目录中的foreach循环都会获取其文件,增加输入并调用stamp方法,直到完成所有文件。在此过程中,顺序很重要。但是,多任务处理(Parallel.ForEach)并不总是保证顺序,据我所知,它会返回首先执行哪个线程,并且还可能损坏i ++功能(如果我错了,请纠正我)。
问题是在这种情况下如何应用多线程?我想最后保存foreach的值,将其传递给标记方法,并让该方法一次标记x文件数量。我不知道是否可能或如何申请。
这是我的水印方法:
//text comes from the foreach already set.
public void waterMark(string text, string sourcePath, string destinationPathh)
{
using (Bitmap bitmap = new Bitmap(sourcePath))
{
//somecode
using (Graphics graphics = Graphics.FromImage(tempBitmap))
{
//somecode
tempBitmap.Save(destinationPathh, ImageFormat.Tiff);
//Erroe^: a generic error occurred in gdi+
//I think due to trying to save multiple files at once
}
}
}
foreach循环:
var files = folder.GetFiles();
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (file, state,indexer) =>
{
//somecode that calls the waterMark method in multiple spots as of now
});
谢谢你。
[overload of Parallel.ForEach
还为正在处理的项目提供索引:
Parallel.ForEach
您可以使用它以线程安全的方式跟踪索引。
关于GDI +的东西(Parallel.ForEach(someEnumerable, (val, state, idx) => Console.WriteLine(idx))
),我认为只要您使用单个线程与位图进行所有交互,您就很安全。在实例化和处置之间,请勿尝试使用Bitmap
做任何聪明的事情。