How to stop the async method process?

init a video file and starting a timer:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private void InitVideoFile(string videoFileName)
{
_videoCapture = new VideoCapture(videoFileName);
_totalFrames = _videoCapture.FrameCount;
// Configure the trackBarFrames
trackBarFrames.Minimum = 0;
trackBarFrames.Maximum = _totalFrames - 1;
trackBarFrames.TickFrequency = 1;
trackBarFrames.Value = 0;
// Display the first frame for drawing the ROI
_firstFrame = new Mat();
if (_videoCapture.Read(_firstFrame))
{
Bitmap bitmap = BitmapConverter.ToBitmap(_firstFrame);
UpdateControl(bitmap.Width, bitmap.Height);
pictureBoxFrames.Image = bitmap;
labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame
}
_timer = new System.Windows.Forms.Timer();
_timer.Interval = 30; // Adjust as needed
_timer.Tick += ProcessFrame;
}
</code>
<code>private void InitVideoFile(string videoFileName) { _videoCapture = new VideoCapture(videoFileName); _totalFrames = _videoCapture.FrameCount; // Configure the trackBarFrames trackBarFrames.Minimum = 0; trackBarFrames.Maximum = _totalFrames - 1; trackBarFrames.TickFrequency = 1; trackBarFrames.Value = 0; // Display the first frame for drawing the ROI _firstFrame = new Mat(); if (_videoCapture.Read(_firstFrame)) { Bitmap bitmap = BitmapConverter.ToBitmap(_firstFrame); UpdateControl(bitmap.Width, bitmap.Height); pictureBoxFrames.Image = bitmap; labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame } _timer = new System.Windows.Forms.Timer(); _timer.Interval = 30; // Adjust as needed _timer.Tick += ProcessFrame; } </code>
private void InitVideoFile(string videoFileName)
{
    _videoCapture = new VideoCapture(videoFileName);
    _totalFrames = _videoCapture.FrameCount;

    // Configure the trackBarFrames
    trackBarFrames.Minimum = 0;
    trackBarFrames.Maximum = _totalFrames - 1;
    trackBarFrames.TickFrequency = 1;
    trackBarFrames.Value = 0;

    // Display the first frame for drawing the ROI
    _firstFrame = new Mat();
    if (_videoCapture.Read(_firstFrame))
    {
        Bitmap bitmap = BitmapConverter.ToBitmap(_firstFrame);
        UpdateControl(bitmap.Width, bitmap.Height);
        pictureBoxFrames.Image = bitmap;
        labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame
    }

    _timer = new System.Windows.Forms.Timer();
    _timer.Interval = 30; // Adjust as needed
    _timer.Tick += ProcessFrame;
}

then on a stop button click event i stop the timer:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private void buttonStop_Click(object sender, EventArgs e)
{
_timer.Stop();
trackBarFrames.Value = 0;
buttonStart.Enabled = true;
buttonStop.Enabled = false;
btnLoadVideo.Enabled = true;
trackBarFrames.Enabled = true;
progressBarAnalysis.Value = 0;
labelStatus.Text = "Ready";
if (_firstFrame != null)
{
pictureBoxFrames.Image = BitmapConverter.ToBitmap(_firstFrame);
labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame
}
}
</code>
<code>private void buttonStop_Click(object sender, EventArgs e) { _timer.Stop(); trackBarFrames.Value = 0; buttonStart.Enabled = true; buttonStop.Enabled = false; btnLoadVideo.Enabled = true; trackBarFrames.Enabled = true; progressBarAnalysis.Value = 0; labelStatus.Text = "Ready"; if (_firstFrame != null) { pictureBoxFrames.Image = BitmapConverter.ToBitmap(_firstFrame); labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame } } </code>
private void buttonStop_Click(object sender, EventArgs e)
{
    _timer.Stop();
    trackBarFrames.Value = 0;
    buttonStart.Enabled = true;
    buttonStop.Enabled = false;
    btnLoadVideo.Enabled = true;
    trackBarFrames.Enabled = true;
    progressBarAnalysis.Value = 0;
    labelStatus.Text = "Ready";
    
    if (_firstFrame != null)
    {
        pictureBoxFrames.Image = BitmapConverter.ToBitmap(_firstFrame);
        labelFrames.Text = $"Displaying frame 1/{_totalFrames}"; // Show 1 as the first frame
    }
}

then in the Process event sometimes it stops but sometimes after stopping the timer the code in the event is keep running like finish if it was in the middle of a task and then i see the progressBarAnalysis.Value raising a bit again after it was reset to 0 and then it stops and the progressBarAnalysis.Value stay on the last value it was.

how can i stop the process in the async ProcessFrame event? stop it completely when clicking the stop button.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private async void ProcessFrame(object sender, EventArgs e)
{
using (Mat frame = new Mat())
{
if (_videoCapture.Read(frame))
{
// Update the ROI if tracking is enabled
if (_tracking && _firstFrame != null)
{
_roiPictureboxFrames = UpdateROI(_firstFrame, frame, _roiPictureboxFrames);
}
// Ensure ROI is within frame bounds
_roiPictureboxFrames = EnsureROIWithinBounds(frame, _roiPictureboxFrames);
// Display each frame in pictureBoxFrame
pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame);
// Process and analyze the frame
(Mat analyzedFrame, bool segmentDetected, bool blinkDetected) = await Task.Run(() => AnalyzeFrame(frame, _currentFrame));
if (analyzedFrame != null)
{
pictureBoxPoints.Image = BitmapConverter.ToBitmap(analyzedFrame);
labelStatus.Text = $"Segment detected in frame {_currentFrame}.";
}
else
{
pictureBoxPoints.Image = null; // Clear the PictureBox if no segments are detected
labelStatus.Text = $"Processing frame {_currentFrame}/{_totalFrames}.";
}
// Update progress
trackBarFrames.Value = _currentFrame;
_videoCapture.Set(VideoCaptureProperties.PosFrames, _currentFrame);
pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame);
labelFrames.Text = $"Displaying frame {_currentFrame + 1}/{_totalFrames}"; // Add 1 to display the frame number starting from 1
progressBarAnalysis.Value = (int)((double)_currentFrame / _totalFrames * 100);
_currentFrame++;
// Update status label
labelStatus.Text = segmentDetected ? $"Segment detected in frame {_currentFrame}." : $"Processing frame {_currentFrame}/{_totalFrames}";
if (_currentFrame >= _totalFrames)
{
progressBarAnalysis.Value = 100;
_timer.Stop();
labelStatus.Text = "Analysis complete.";
}
// Store the current frame as the previous frame for the next iteration
_firstFrame = frame.Clone();
}
else
{
_timer.Stop();
labelStatus.Text = "Error reading video file.";
}
}
}
</code>
<code>private async void ProcessFrame(object sender, EventArgs e) { using (Mat frame = new Mat()) { if (_videoCapture.Read(frame)) { // Update the ROI if tracking is enabled if (_tracking && _firstFrame != null) { _roiPictureboxFrames = UpdateROI(_firstFrame, frame, _roiPictureboxFrames); } // Ensure ROI is within frame bounds _roiPictureboxFrames = EnsureROIWithinBounds(frame, _roiPictureboxFrames); // Display each frame in pictureBoxFrame pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame); // Process and analyze the frame (Mat analyzedFrame, bool segmentDetected, bool blinkDetected) = await Task.Run(() => AnalyzeFrame(frame, _currentFrame)); if (analyzedFrame != null) { pictureBoxPoints.Image = BitmapConverter.ToBitmap(analyzedFrame); labelStatus.Text = $"Segment detected in frame {_currentFrame}."; } else { pictureBoxPoints.Image = null; // Clear the PictureBox if no segments are detected labelStatus.Text = $"Processing frame {_currentFrame}/{_totalFrames}."; } // Update progress trackBarFrames.Value = _currentFrame; _videoCapture.Set(VideoCaptureProperties.PosFrames, _currentFrame); pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame); labelFrames.Text = $"Displaying frame {_currentFrame + 1}/{_totalFrames}"; // Add 1 to display the frame number starting from 1 progressBarAnalysis.Value = (int)((double)_currentFrame / _totalFrames * 100); _currentFrame++; // Update status label labelStatus.Text = segmentDetected ? $"Segment detected in frame {_currentFrame}." : $"Processing frame {_currentFrame}/{_totalFrames}"; if (_currentFrame >= _totalFrames) { progressBarAnalysis.Value = 100; _timer.Stop(); labelStatus.Text = "Analysis complete."; } // Store the current frame as the previous frame for the next iteration _firstFrame = frame.Clone(); } else { _timer.Stop(); labelStatus.Text = "Error reading video file."; } } } </code>
private async void ProcessFrame(object sender, EventArgs e)
{
    using (Mat frame = new Mat())
    {
        if (_videoCapture.Read(frame))
        {
            // Update the ROI if tracking is enabled
            if (_tracking && _firstFrame != null)
            {
                _roiPictureboxFrames = UpdateROI(_firstFrame, frame, _roiPictureboxFrames);
            }

            // Ensure ROI is within frame bounds
            _roiPictureboxFrames = EnsureROIWithinBounds(frame, _roiPictureboxFrames);

            // Display each frame in pictureBoxFrame
            pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame);

            // Process and analyze the frame
            (Mat analyzedFrame, bool segmentDetected, bool blinkDetected) = await Task.Run(() => AnalyzeFrame(frame, _currentFrame));
            if (analyzedFrame != null)
            {
                pictureBoxPoints.Image = BitmapConverter.ToBitmap(analyzedFrame);
                labelStatus.Text = $"Segment detected in frame {_currentFrame}.";
            }
            else
            {
                pictureBoxPoints.Image = null; // Clear the PictureBox if no segments are detected
                labelStatus.Text = $"Processing frame {_currentFrame}/{_totalFrames}.";
            }

            // Update progress
            trackBarFrames.Value = _currentFrame;
            _videoCapture.Set(VideoCaptureProperties.PosFrames, _currentFrame);
            pictureBoxFrames.Image = BitmapConverter.ToBitmap(frame);
            labelFrames.Text = $"Displaying frame {_currentFrame + 1}/{_totalFrames}"; // Add 1 to display the frame number starting from 1

            progressBarAnalysis.Value = (int)((double)_currentFrame / _totalFrames * 100);
            _currentFrame++;
            // Update status label
            labelStatus.Text = segmentDetected ? $"Segment detected in frame {_currentFrame}." : $"Processing frame {_currentFrame}/{_totalFrames}";

            if (_currentFrame >= _totalFrames)
            {
                progressBarAnalysis.Value = 100;
                _timer.Stop();
                labelStatus.Text = "Analysis complete.";
            }

            // Store the current frame as the previous frame for the next iteration
            _firstFrame = frame.Clone();
        }
        else
        {
            _timer.Stop();
            labelStatus.Text = "Error reading video file.";
        }
    }
}

i tried to add at the top of the ProcessFrame event code this two lines:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if (!_timer.Enabled)
return;
</code>
<code>if (!_timer.Enabled) return; </code>
if (!_timer.Enabled)
    return;

but it didn’t help much.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật