[英]how to run concurrent tasks in c#
我编写了一个控制台应用程序来处理图像文件并将其与数据库记录匹配。
图像文件全部位于文件存储区的不同文件夹中,每天一个文件夹,因此文件存储区的结构应为
FileStore -> Day1 -> Images -------------------> Indexfile.csv
因此,我的程序将打开每个文件夹并获取索引文件,并将图像与数据库中的记录进行匹配。
这些文件夹很大,其中一些具有90000多个图像,因此我想运行5个不同的任务,每个任务抓取一个不同的文件夹并并行处理它们,我尝试创建5个任务,并且工作正常,但我不这样做5个任务之一完成后,便不知道如何开始新任务。
任何指针将不胜感激。
谢谢。
最简单的方法是创建一个包含所有文件的列表,并使用Parallel.ForEach
,签出文档https://msdn.microsoft.com/zh-cn/library/dd460720%28v=vs.110%29.aspx?f = 255&MSPPError = -2147217396
示例代码:
// A simple source for demonstration purposes. Modify this path as necessary.
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)
// Be sure to add a reference to System.Drawing.dll.
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);
var bitmap = new Bitmap(currentFile);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
bitmap.Save(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 and method invocation
});
// Keep the console window open in debug mode.
Console.WriteLine("Processing complete. Press any key to exit.");
Console.ReadKey();
您应该在任务列表中使用WhenAny
(非阻塞)或WaitAny
(阻塞)。 然后从列表中删除所有已完成的任务并添加新任务。
List<Task<...>> tasks = ... // put your 5 tasks inside this list.
while(condintion)
{
await Task.WhenAny(tasks);
tasks.RemoveAll(t => t.IsCompleted);
while(tasks.Count < 5 && condintion)
{
Task<...> newTask = ... // run your task
tasks.Add(newTask);
}
}
放置适当的条件,以便仅当获取所有文件夹时才为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.