Возникает ошибка в программе "Объект в данный момент используется другим приложением", используются библиотеки AccordVideo

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using Accord.Video;
using Accord.Video.DirectShow;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Accord.Video.FFMPEG;
using System.Threading;


namespace Multi_Doctor
{
    public partial class HDMD_VID : Form
    {
        private System.Drawing.Font selectedFont = new System.Drawing.Font("Times New Roman", 14, FontStyle.Regular, GraphicsUnit.Point);
        private VideoCaptureDevice videoSource;        
        private FilterInfoCollection videoDevices;
        private int screenshotNumber = 1;
        private VideoCaptureDevice currentVideoSource;
        private Color currentBrushColor = Color.Black;
        private Bitmap originalBitmap;        
        private bool isPenToolActive = false;
        private Point? previousPoint = null;        
        private bool isSquareToolActive = false;
        private System.Drawing.Rectangle cropRect;  
        private bool isCropping = false;
        private Point? startPoint = null;
        private bool isCircleToolActive = false;
        private bool isTextToolActive = false;
        private string patientName;
        private int patientId;
        private string doctorName;
        private string anamnesis;
        private bool isZoomActive = false;
        private const int ZOOM_SIZE = 300;
        private const int ZOOM_FACTOR = 2;
        private Bitmap zoomCache;                
        private Stack<Bitmap> undoStack = new Stack<Bitmap>();
        private Stack<Bitmap> redoStack = new Stack<Bitmap>();        
        private bool hasChanges = false;
        private DrawingTool currentTool = DrawingTool.None;
        private VideoFileWriter videoWriter;        
        private DateTime lastScreenshotTime = DateTime.MinValue;
        private Size originalSize;
        private Bitmap workingBitmap;
        private string currentPatientDirectory;
        private Thread videoRecordingThread;
        private object videoRecordingLock = new object();
        private bool isVideoRecording = false;
        private Bitmap currentVideoFrame = null;
        private readonly object frameLock = new object();
        private System.Windows.Forms.Label lb_rec;
        private System.Windows.Forms.Timer blinkTimer;

        public HDMD_VID(Patient selectedPatient)
        {
            InitializeComponent();
            blinkTimer = new System.Windows.Forms.Timer();
            blinkTimer.Interval = 500;  // 500 мс = 0.5 секунды
            blinkTimer.Tick += BlinkTimer_Tick;
            this.patientName = selectedPatient.Name;
            this.patientId = selectedPatient.PatientNumber;
            this.anamnesis = selectedPatient.Anamnesis;
            this.doctorName = selectedPatient.Doctor;            
            workingBitmap = null;            
            this.Load += (sender, e) =>
            {
                LoadVideoDevices();
            };
        }

        private void BlinkTimer_Tick(object sender, EventArgs e)
        {
            lb_rec.Visible = !lb_rec.Visible;
        }

        private void HDMD_VID_Load(object sender, EventArgs e)
        {
            lb_name.Text = patientName;
            lb_hisnumb.Text = patientId.ToString();
            tb_vrach.Text = doctorName;
            tb_fio.Text = patientName;
            tb_hisnumb.Text = patientId.ToString();
            tb_anamnesis.Text = anamnesis;            
            this.WindowState = FormWindowState.Maximized;
            string baseDirectory = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PATIENT_BASE");
            string currentDate = DateTime.Now.ToString("ddMMyyyy");
            currentPatientDirectory = System.IO.Path.Combine(baseDirectory, $"{patientName}_{currentDate}");

            if (!Directory.Exists(currentPatientDirectory))
            {
                Directory.CreateDirectory(currentPatientDirectory);
            }
            else
            {
                LoadImagesFromDirectory(currentPatientDirectory);
            }
        }
        private void Cb_resol_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (currentVideoSource != null && currentVideoSource.IsRunning)
            {
                currentVideoSource.NewFrame -= VideoSource_NewFrame;
                currentVideoSource.SignalToStop();
                currentVideoSource.WaitForStop();
                Btn_start_Click(sender, e);
            }
        }

        private void Cb_cam_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (videoSource != null && videoSource.IsRunning)
            {
                videoSource.SignalToStop();
                videoSource.WaitForStop();
            }

            int selectedIndex = cb_cam.SelectedIndex;
            if (selectedIndex >= 0)
            {
                string selectedCameraName = cb_cam.Items[selectedIndex].ToString();
                Accord.Video.DirectShow.FilterInfo selectedCamera = videoDevices[selectedIndex];
                videoSource = new VideoCaptureDevice(selectedCamera.MonikerString);
                cb_resol.Items.Clear();
                foreach (var videoFormat in videoSource.VideoCapabilities)
                {
                    cb_resol.Items.Add(videoFormat.FrameSize);
                }
                if (cb_resol.Items.Count > 0)
                {
                    cb_resol.SelectedIndex = 0;
                }
                cb_framesek.Items.Clear();
                foreach (var videoFormat in videoSource.VideoCapabilities)
                {
                    cb_framesek.Items.Add(videoFormat.MaximumFrameRate);
                }

                if (cb_framesek.Items.Count > 0)
                {
                    cb_framesek.SelectedIndex = 0;
                }
            }
        }
        private void LoadVideoDevices()
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo device in videoDevices)
            {
                
                cb_cam.Items.Add(device.Name);
            }

            if (cb_cam.Items.Count > 0)
            {
                cb_cam.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("No video sources found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }           

        private async void Btn_start_Click(object sender, EventArgs e)
        {
            await StartVideoSourceAsync();
        }

        private async Task StartVideoSourceAsync()
        {
            if (videoSource == null || !videoSource.IsRunning)
            {
                if (cb_cam.SelectedIndex >= 0 && cb_cam.SelectedIndex < videoDevices.Count)
                {
                    videoSource = new VideoCaptureDevice(videoDevices[cb_cam.SelectedIndex].MonikerString);

                    foreach (var resolution in videoSource.VideoCapabilities)
                    {
                        if (resolution.FrameSize.Width == 1920 && resolution.FrameSize.Height == 1080)
                        {
                            videoSource.VideoResolution = resolution;
                            break;
                        }
                    }
                    videoSource.DesiredFrameRate = 25;

                    videoSource.NewFrame += new NewFrameEventHandler(VideoSource_NewFrame);

                    await Task.Run(() => videoSource.Start());
                }
            }
        }
        private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            lock (videoRecordingLock)
            {
                if (isVideoRecording && videoWriter != null && videoWriter.IsOpen)
                {
                    lock (frameLock)
                    {
                        // Освобождение старого изображения
                        currentVideoFrame?.Dispose();

                        currentVideoFrame = (Bitmap)eventArgs.Frame.Clone();
                    }
                }

                Bitmap newFrame = (Bitmap)eventArgs.Frame.Clone();
                workingBitmap?.Dispose();
                workingBitmap = newFrame;
                pb_camera.Image = (Bitmap)workingBitmap.Clone();
            }
        }
        private async void Btn_screenshot_Click(object sender, EventArgs e)
        {
            if (!videoSource.IsRunning || pb_camera.Image == null)
            {
                MessageBox.Show("Нажмите кнопку \"Начать\"");
                return;
            }                     

            try
            {
                StopVideoStream();
                string formattedTime = DateTime.Now.ToString("yyyyMMddHHmm");
                string surname = lb_fio1.Text.Trim();
                string fileBaseName = $"{surname}_{formattedTime}_{screenshotNumber}";
                string fileName = fileBaseName + ".jpg";
                
                string imagePath = Path.Combine(currentPatientDirectory, fileName);
                using (MemoryStream ms = new MemoryStream())
                {
                    pb_camera.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                    // Сбрасываем позицию потока перед созданием нового Bitmap
                    ms.Position = 0;

                    using (Bitmap bitmapWithWatermark = new Bitmap(ms))
                    {
                        AddWatermark(bitmapWithWatermark);
                        bitmapWithWatermark.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
                var panel = new TableLayoutPanel();
                panel.AutoSize = true;
                panel.Dock = DockStyle.Left;

                PictureBox pb = new PictureBox();
                using (var tempImage = System.Drawing.Image.FromFile(imagePath))
                {
                    pb.Image = new Bitmap(tempImage);
                }

                double aspectRatio = (double)pb.Image.Width / pb.Image.Height;
                pb.Width = flp_imagelist.Width;
                pb.Height = (int)(pb.Width / aspectRatio);
                pb.SizeMode = PictureBoxSizeMode.Zoom;
                pb.Tag = imagePath;                
                Button selectButton = new Button();
                selectButton.Text = "Выбрать";
                selectButton.AutoSize = true;
                selectButton.Click += SelectButton_Click;                
                Button deleteButton = new Button();
                deleteButton.Text = "Удалить";
                deleteButton.AutoSize = true;
                deleteButton.Click += DeleteButton_Click;                
                Button openButton = new Button();                
                panel.Controls.Add(pb);
                pb.MouseClick += PictureBox_MouseClick;
                panel.Controls.Add(selectButton);
                panel.Controls.Add(deleteButton);                
                
                this.Invoke(new Action(() =>
                {
                    flp_imagelist.Controls.Add(panel);
                }));
                screenshotNumber++;

                await StartVideoSourceAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Произошла ошибка: {ex.Message}");
            }
        }
private void StopVideoStream()
        {
            if (videoSource != null && videoSource.IsRunning)
            {
                videoSource.SignalToStop();
                videoSource.WaitForStop();
                videoSource.NewFrame -= VideoSource_NewFrame;
                videoSource = null;
            }
        }
        
        private void Btn_recvid_Click_1(object sender, EventArgs e)
        {
            StartVideoRecording();
        }

        private void StartVideoRecording()
        {            
            lock (videoRecordingLock)
            {
                if (!isVideoRecording)
                {
                    string formattedTime = DateTime.Now.ToString("yyyyMMddHHmm");
                    string surname = lb_fio1.Text.Trim();
                    string videoFileName = $"{surname}_{formattedTime}.mp4";
                    string videoPath = Path.Combine(currentPatientDirectory, videoFileName);

                    videoWriter = new VideoFileWriter();
                    videoWriter.Open(videoPath, 1920, 1080, 30, VideoCodec.H264, bitRate: 3000000);

                    isVideoRecording = true;

                    videoRecordingThread = new Thread(() =>
                    {
                        while (isVideoRecording)
                        {
                            Bitmap frameToWrite = null;

                            lock (frameLock)
                            {
                                if (currentVideoFrame != null)
                                {
                                    frameToWrite = (Bitmap)currentVideoFrame.Clone();
                                }
                            }

                            if (frameToWrite != null)
                            {
                                videoWriter.WriteVideoFrame(frameToWrite);
                                frameToWrite.Dispose();
                            }
                        }
                    });

                    videoRecordingThread.Start();
                }                
                lb_rec.Visible = true;
                blinkTimer.Start();
            }
        }

        private void Btn_stoprec_Click(object sender, EventArgs e)
        {
            StopVideoRecording();
        }

        private void StopVideoRecording()
        {            
            lock (videoRecordingLock)
            {
                if (isVideoRecording)
                {
                    isVideoRecording = false;
                    videoRecordingThread.Join(); 

                    if (videoWriter != null)
                    {
                        videoWriter.Close();
                        videoWriter.Dispose();
                        videoWriter = null;
                    }
                }
            }            
            blinkTimer.Stop();
            lb_rec.Visible = false;
        }
   
System.InvalidOperationException: В данный момент объект используется другим процессом.
   в System.Drawing.Graphics.CheckErrorStatus(Int32 status)
   в System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
   в System.Drawing.Graphics.DrawImage(Image image, Rectangle rect)
   в System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
   в System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
   в System.Windows.Forms.Control.WmPaint(Message& m)
   в System.Windows.Forms.Control.WndProc(Message& m)
   в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
System.InvalidOperationException HResult=0x80131509 Сообщение = В данный момент объект используется другим процессом. Источник = System.Drawing 
Трассировка стека: 
at System.Drawing.Graphics.CheckErrorStatus(Int32 status) 
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height) 
at System.Drawing.Graphics.DrawImage(Image image, Rectangle rect) 
at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe) 
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) 
at System.Windows.Forms.Control.WmPaint(Message& m) 
at System.Windows.Forms.Control.WndProc(Message& m) 
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

вот сейчас получилось дождаться от VS, все же проблема возникает после определенных манипуляций, т.е. сделал снимок, или поставил запись видео, и после этого по времени по разному, может через 3 минуты, может через 20 минут ошибка выйти


Ответы (0 шт):