【发布时间】:2020-05-07 18:53:46
【问题描述】:
我有一个程序可以让用户 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
});
提前谢谢你。
【问题讨论】:
-
另见:Read and process files in parallel C#。有Parallel.For Method 方法给你一个索引。
标签: c# asp.net multithreading