My application has a List of Tasks. Each Task launches a FFMPEG process that requires a lot of resources on my machine. At times, this list can contain 200+ processes to FFMPEG. While processing, my memory is at 99% and everything freezes up.
I need to limit the amount of processes that can run at one time. I have read a little about SemaphoreSlim; however, I cannot wrap my mind around it's implementation.
Is this a solution for this particular problem and if so, any ideas on how to implement it in my code?
Below is my code:
public async System.Threading.Tasks.Task GetVideoFiles()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
if (openFileDialog.ShowDialog() == true)
{
AllSplices.Clear();
AllSplices = new ObservableCollection<SpliceModel>();
IsBusy = true;
IsBusyMessage = "Extracting Metadata";
IsBusyBackgroundVisible = "Visible";
NotifyPropertyChanged(nameof(IsBusy));
NotifyPropertyChanged(nameof(IsBusyMessage));
NotifyPropertyChanged(nameof(IsBusyBackgroundVisible));
metaTasks = new List<Task<VideoFileModel>>();
extractFramesTask = new List<System.Threading.Tasks.Task>();
foreach (string file in openFileDialog.FileNames)
{
FileInfo fileInfo = new FileInfo(file);
bool canAdd = true;
var tempFileName = fileInfo.Name;
foreach (var video in AllVideos)
{
if (file == video.VideoPath)
{
canAdd = false;
break;
}
if (video.VideoName.Contains(tempFileName))
{
video.VideoName = "_" + video.VideoName;
}
}
if (canAdd)
{
metaTasks.Add(System.Threading.Tasks.Task.Run(() => ProcessMetaData(file)));
}
}
var metaDataResults = await System.Threading.Tasks.Task.WhenAll(metaTasks);
foreach (var vid in metaDataResults)
{
if(vid == null)
{
continue;
}
vid.IsNewVideo = true;
AllVideos.Add(vid);
// This list of task launches up to 200 video processing processes to FFMPEG
extractFramesTask.Add(System.Threading.Tasks.Task.Run(() => ExtractFrames(vid)));
vid.IsProgressVisible = "Visible";
TotalDuration += vid.VideoDuration;
vid.NumberOfFrames = Convert.ToInt32(vid.VideoDuration.TotalSeconds * 30);
_ = ReportProgress(vid);
}
IsBusyMessage = "Importing Frames";
NotifyPropertyChanged(nameof(IsBusyMessage));
await System.Threading.Tasks.Task.WhenAll(extractFramesTask);
}