我正在撰寫一個程式,它會搜索計算機的整個檔案系統,以銷毀任何符合某些引數的檔案。我希望程式盡可能快地運行,并利用盡可能多的資源來實作這一點(值得注意的是,在此程序發生時,預計用戶不會完成任何其他作業)。為此,我撰寫了一個方法,它接受一個目標目錄,搜索其中的所有檔案,然后為每個子目錄排隊一個新任務。目前這是通過將目錄的路徑傳遞到主執行緒監控并用于實際初始化新任務的佇列中來完成的,如下所示:
static class DriveHandler
{
internal static readonly List<string> fixedDrives = GetFixedDrives();
private static readonly ConcurrentQueue<string> _targetPathQueue = new ConcurrentQueue<string>();
private static int _threadCounter = 0;
internal static void WipeDrives()
{
foreach (string driveLetter in fixedDrives)
{
Interlocked.Increment(ref _threadCounter);
Task.Run(() => WalkDrive(driveLetter));
}
while (Volatile.Read(ref _threadCounter) > 0 || !_targetPathQueue.IsEmpty)
{
if (_targetPathQueue.TryDequeue(out string path))
{
Interlocked.Increment(ref _threadCounter);
Task.Run(() => WalkDrive(path));
}
}
}
private static void WalkDrive(string directory)
{
foreach (string file in Directory.GetFiles(directory))
{
//If file meets conditions, delete
}
string[] subDirectories = Directory.GetDirectories(directory);
if (subDirectories.Length != 0)
{
foreach (string subDirectory in subDirectories)
{
_targetPathQueue.Enqueue(subDirectory);
}
}
else { } //do other stuff;
Interlocked.Decrement(ref _threadCounter);
}
}
我的問題是,從已經運行的任務中初始化新任務以避免浪費處理器時間來監控佇列是否安全/值得?看起來像這樣的東西:
static class DriveHandler
{
internal static readonly List<string> fixedDrives = GetFixedDrives();
private static int _threadCounter = 0;
internal static void WipeDrives()
{
foreach (string driveLetter in fixedDrives)
{
Interlocked.Increment(ref _threadCounter);
Task.Run(() => WalkDrive(driveLetter));
}
while (Volatile.Read(ref _threadCounter) > 0)
{
Thread.Sleep(5000);
}
}
private static void WalkDrive(string directory)
{
foreach (string file in Directory.GetFiles(directory))
{
//If file meets conditions, delete
}
string[] subDirectories = Directory.GetDirectories(directory);
if (subDirectories.Length != 0)
{
foreach (string subDirectory in subDirectories)
{
Interlocked.Increment(ref _threadCounter);
Task.Run(() => WalkDrive(path));
}
}
else { } //do other stuff;
Interlocked.Decrement(ref _threadCounter);
}
}
我當然需要每項任務一旦完成就死掉,這樣做會讓舊任務成為新任務的父母并讓他們活著直到他們所有的孩子都完成了嗎?
非常感謝!
uj5u.com熱心網友回復:
第一個問題:
Task.Run(() => WalkDrive(路徑));
這是一種火而忘卻的時尚,在這種情況下這樣做不是一件好事,為什么?因為很有可能,您在硬碟上擁有的檔案和路徑比機器擁有的 CPU 和記憶體容量要多得多(任務消耗記憶體,而不僅僅是 CPU)。解雇并忘記,因此得名,你不斷產生任務而不是await他們。
我的問題是,從已經運行的任務中初始化新任務以避免浪費處理器時間來監控佇列是否安全/值得?
這是有效的,沒有什么可以阻止你這樣做,但你已經在浪費資源,為什么每次都產生新的任務?您已經運行了一個,只需將其設定為長時間運行的后臺任務并保持運行,只有兩個執行緒(我假設一個是(UI/面向用戶的)執行緒)和一個在作業。所有這些鎖和任務的產生都會損害您的性能并浪費所有資源 CPU 記憶體分配。
如果您想通過并行執行加快速度您可以將路徑添加到并發佇列,并且只有 10-100 個并發任務 MAX 或其他任何東西,至少您有一個上限,您可以控制代碼并行執行的數量.
而 conccurent-queue 不為空且沒有人請求取消操作:
- 從基本路徑開始
- 獲取所有子路徑并將它們排入并發佇列
- 處理該路徑內的檔案
- 使當前基本路徑作為佇列中的下一個可用項
- 重新開始。
您只需啟動最大數量的并發任務即可。
您的主回圈/while 條件類似于:
private async Task StartAsync(CancellationToken cancellationToken)
{
var tasks = new List<Task>();
for (int i = 0; i < MaxConcurrentTasks; i )
{
tasks.Add(Task.Run(() => ProcessPath(initialPathHere), cancellationToken));
}
await Task.WhenAll(tasks);
}
然后沿著這些思路:
private static async Task ProcessPath(string path, CancellationToken cancellationToken)
{
while(concurrentDictionary.Count > 0 && !cancellationToken.IsCancellationRequested)
{
foreach(var subPath in System.IO.Directory.EnumerateDirectories(path))
{
//Enqueue the subPath into the concurrent dictionary
}
//Once finished, process files in the current path
foreach (var file in path)
{
}
path = concurrentDictionary.Dequeue();
}
}
還沒有檢查語法,但我認為這是一個好的演算法可以做到的。另外,請記住,當任務完成其當前作業時,此行中的佇列可能為空,因此請相應地修改該代碼。
path = concurrentDictionary.Dequeue();
最后注意事項:
- 考慮任務和 Parallel.Invok/execute 之間的交易
- 考慮使用
BackgroundServices它們經過微調以長期運行,具體取決于您的代碼和要求 - 為了提高績效,請記住黃金法則,
measure early. 從測量開始,手頭已經有一些指標,所以稍后如果你想加快速度,你至少知道你現在可以做多少,所以你重構并再次測量并比較,然后你會知道你是否離目標越來越近或越來越遠。 - 確保您正確地進行了并發/并行處理,否則它將不利于您。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461343.html
上一篇:沒有二進制信號量會發生什么
