private void EncodeAndSave() { print("SCREENRECORDER IO THREAD STARTED"); while (threadIsProcessing) { if (frameQueue.Count > 0) { // Generate file path string path = GetFileFullName(savingFrameNumber.ToString()); // Dequeue the frame, encode it as a bitmap, and write it to the file using (FileStream fileStream = new FileStream(path, FileMode.Create)) { BitmapEncoder.WriteBitmap(fileStream, screenWidth, screenHeight, frameQueue.Dequeue()); fileStream.Close(); } // Done savingFrameNumber++; print("Saved " + savingFrameNumber + " frames. " + frameQueue.Count + " frames remaining."); } else { if (terminateThreadWhenDone) { break; } Thread.Sleep(1); } } terminateThreadWhenDone = false; threadIsProcessing = false; if (!string.IsNullOrEmpty(FFmpegToolPath)) { var ffmpeg = new Ffmpeg(FFmpegToolPath, persistentDataPath); ffmpeg.FrameRate = frameRate; ffmpeg.InputFileName = GetFileFullName("%d"); ffmpeg.Run(); print("Deleting files..."); var dir = new DirectoryInfo(persistentDataPath); var files = dir.GetFiles(); foreach (var f in files) { File.Delete(f.FullName); } } print("SCREENRECORDER IO THREAD FINISHED"); }