locked
How to stop a function with a button RRS feed

  • Question

  • Hello,

    With C# Winforms, I have a button which allows to start a function and I would like to make another button which allows to stop the function executed.

    private void buttonWriteFast_Click (object sender, EventArgs e)
    {
       WriteFast();
    }


    private void buttonStop_Click (object sender, EventArgs e)
    {
      //code to stop WriteFast()
    }


    I had thought about threading, but I don't really know threads, and I'm not sure that this is the right solution to my problem.
    Do you have a sample code that can stop the execution of a function by clicking on a button?

    Thanks.

    Monday, July 13, 2020 12:59 AM

All replies

  • You decided against your original handler?

    Nothing wrong with that just you're making things more complex. E.g. even though you'll probably try to make your app responsive I suspect you're not there yet. Your best bet is to solve you original event problem - understanding events is crucial to windows development.

    There's a lot too consider when you make you UI responsive (so, say, you can click another button during a long running task) and much of that is reliant on event handling.

    I can help though if you want to dig further into background tasks.




    • Edited by stevemrf Monday, July 13, 2020 1:13 AM
    Monday, July 13, 2020 1:10 AM

  • I had thought about threading, but I don't really know threads, 

    Everything is explained in MSDN : Using threads and threading
    Monday, July 13, 2020 6:53 AM
  • Hi speed780,
    You can also use the timer control to achieve to requirement.
    Here is a code example you can refer to.

    private void buttonWriteFast_Click(object sender, EventArgs e)
    {
        WriteFast();
    }
    
    private void buttonStop_Click(object sender, EventArgs e)
    {
        timer1.Stop();
    }
    public void WriteFast()
    {
        timer1.Tick += new EventHandler(TimerEventProcessor);     
        timer1.Start();
    }
    int i = 0;
    private  void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
    {
        i++;
        Console.WriteLine(i);
    
    }

    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 13, 2020 9:53 AM
  • Thank you for your reply, but timer1 is not recognized.
    Monday, July 13, 2020 11:07 AM
  • In fact, what is a simple and good solution to do that, please?

    Do you have an example of code?

    Thanks.

    • Edited by speed780 Monday, July 13, 2020 11:09 AM
    Monday, July 13, 2020 11:08 AM
  • In fact, what is a simple and good solution to do that, please?

    Do you have an example of code?

    Thanks.

    There are plenty of samples in MSDN in the posted link...

    Monday, July 13, 2020 11:41 AM
  • See the following.

    And read the comments

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace SomeApp
    {
        /// <summary>
        /// Requires two buttons StartButton and StopButton,
        /// one label MonitorLabel
        /// </summary>
        public partial class Form1 : Form
        {
            private CancellationTokenSource _cancellationTokenSource = 
                new CancellationTokenSource();
    
            /// <summary>
            /// How many time to iterate in Operations.WriteFast
            /// </summary>
            private int _totalIterations = 230;
    
            public Form1()
            {
                InitializeComponent();
    
                // optional event to monitor what's going on
                Operations.OnMonitor += Operations_OnMonitor;
            }
            /// <summary>
            /// Show progress
            /// </summary>
            /// <param name="args"></param>
            private void Operations_OnMonitor(MonitorArgs args)
            {
                MonitorLabel.Text = $"{args.Text} {args.Value}";
            }
            /// <summary>
            /// Start process and watch for cancellation
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private async void StartButton_Click(object sender, EventArgs e)
            {
                StartButton.Enabled = false;
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    _cancellationTokenSource.Dispose();
                    _cancellationTokenSource = new CancellationTokenSource();
                }
    
                try
                {
                    var resultValue = await Operations.WriteFast(
                        _totalIterations, _cancellationTokenSource.Token);
    
                }
                catch (OperationCanceledException oce)
                {
                    // Cancellation from code in stop button
                    MessageBox.Show("Operation cancelled");
                }
                catch (Exception ex)
                {
                    // unknown exception
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    StartButton.Enabled = true;
                }
            }
            /// <summary>
            /// Cancel/stop WriteFast operation
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void StopButton_Click(object sender, EventArgs e)
            {
                _cancellationTokenSource.Cancel();
                StartButton.Enabled = true;
            }
        }
        /// <summary>
        /// Place in a separate file
        /// </summary>
        public class DelegatesModule
        {
            public delegate void MonitorHandler(MonitorArgs args);
        }
        /// <summary>
        /// Place in a separate file
        /// </summary>
        public class MonitorArgs : EventArgs
        {
            public MonitorArgs(string text, int value)
            {
                Text = text;
                Value = value;
            }
    
            public string Text { get; set; }
            public int Value { get; set; }
    
        }
        /// <summary>
        /// Place in a separate file
        /// </summary>
        public class Operations
        {
            public static event DelegatesModule.MonitorHandler OnMonitor;
            /// <summary>
            /// A do nothing method
            /// </summary>
            /// <param name="maxIteration"></param>
            /// <param name="token"></param>
            /// <returns></returns>
            public static async Task<int> WriteFast(int maxIteration, CancellationToken token)
            {
                var currentIndex = 0;
    
                while (currentIndex <= maxIteration - 1)
                {
                    currentIndex += 1;
    
                    await Task.Delay(1, token);
    
                    // do work here
                    Monitor(new MonitorArgs("Working", currentIndex));
                    if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
                }
    
                Monitor(new MonitorArgs("Done", currentIndex));
                return currentIndex;
            }
    
            private static void Monitor(MonitorArgs args)
            {
                OnMonitor?.Invoke(args);
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, July 13, 2020 4:48 PM

  • Hi speed780,
    You can drag the "Timer" control from Toolbox to form directly.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, July 14, 2020 7:18 AM
  • Hi speed780,
    Has your problem been solved? If it is resolved, we suggest that you mark it as the answer. So it can help other people who have the same problem find a solution quickly. If not solved, what problem did you encounter?
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 15, 2020 8:48 AM
  • Thanks, but it is complex. Is there an easier solution?

    Thanks.

    Thursday, July 16, 2020 7:24 PM
  • Thanks, but when I stop the action, the action is paused, and does not return to the initial state when I restart the button.

    In fact, I would like that the stop button stop the action and back to the beginning.

    Thursday, July 16, 2020 7:34 PM
  • Hi speed780,
    You can try the Timer.Dispose method which releases all resources used by the current instance of timer.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, July 17, 2020 9:20 AM