【发布时间】:2021-07-09 19:18:37
【问题描述】:
我的代码可以侦听文件夹并检测放入其中的新文件。
目前,每个删除的新文件都会调用WatcherOnCreated 方法,该方法会创建一个新任务来与其他文件并行加密文件。
我想限制并行文件加密的数量。
我尝试使用计数为 5 的信号量,这样无论放入多少文件,都只能同时进行 5 次加密。
但是,它不起作用,导致我的程序没有响应。
class Test
{
private static LimitEncryptionSemaphore;
public Test()
{
LimitEncryptionSemaphore = new SemaphoreSlim(5);
}
// some function which calls WatcherOnCreated
private void WatcherOnCreated(string filePath, WatcherChangeTypes changeType)
{
string fileName = Path.GetFileName(filePath);
Logger.Debug($"A created item {fileName} was detected in drop folder.");
LimitEncryptionSemaphore.WaitAsync();
// FireAndForget calls Task.Run(Func<Task>) with the callback function
TaskFactory.FireAndForget(async () =>
{
try
{
await ExponentialBackoffPolicy.ExecuteAsync(async () =>
{
using (DeviceData deviceData = ReadDeviceData(filePath))
{
// Raise the event.
await OnDeviceDataAvailable(FolderDevice, deviceData);
}
});
if (FileSystem.Exists(filePath))
{
// Delete the file once the handler is done.
FileSystem.DeleteFile(filePath);
Logger.Debug($"{filePath} was deleted.");
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
finally
{
// Release semaphore
LimitEncryptionSemaphore.Release();
}
});
}
【问题讨论】:
-
我认为您的问题会更多地与codereview.stackexchange.com 的主题有关,您应该尝试在那里发帖。
-
您的代码限制为 10 而不是 5。
-
请注意,虽然您已经编辑了您的问题以尽量减少基于意见的问题(这就是前两个接近投票的原因),但它仍然缺少可靠地重现您的问题的 minimal reproducible example描述,因此是第三次也是最后一次近距离投票。
标签: c# .net multithreading task-parallel-library semaphore