I am new to C # and object oriented programming in general. I am trying to embed the Cancel button in my GUI so that the user can stop it in the middle of the process.
I read this question: How to implement the Stop / Cancel button? and determined that background work should be a good option for me, but the example below doesn’t explain how to pass arguments to backgroundWorker.
My problem is that I don't know how to pass an argument to backgroundWorker so that it stops the process; I was only able to make backgroundWorker stop.
I created the following code to try and find out where my form has two buttons (buttonStart and buttonStop) and backgroundWorker (backgroundWorkerStopCheck):
using System; using System.ComponentModel; using System.Windows.Forms; using System.Threading; using System.Timers; namespace TestBackgroundWorker { public partial class Form1 : Form { public Form1() { InitializeComponent();
The code, if it worked correctly, would just sit there for five seconds after the user pressed the Start button before turning on the Start button again or quickly activated the Start button if the user pressed Stop.
There are two problems with this code that I'm not sure how to handle:
1) The myTimer_Elapsed method throws an InvalidOperationException when it tries to turn on the Start button because the "cross-flow operation is invalid." How to avoid cross-flow operations?
2) Currently, backgroundWorker is not doing anything because I don’t know how to give it arguments, so when it is canceled, it stops the timer.
I would be grateful for any help!
source share