簡體   English   中英

如何在C#中運行並發任務

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM