That's more complex than it seems at first glance.
The problem is that unless you specifically code it otherwise, your application has only one thread. So if you start a long operation on a button click:
private void MyButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10000000; i++)
{
DoIt();
}
}
Then nothing else will happen until the long operation is completed - because the thread is busy doing the long operation.
In order to get the button to work at all in order to stop the operation, you have to move the operation to a new thread. That's not difficult, but it does need a little work. The easiest way to do it is to use a BackgroundWorker:
private BackgroundWorker worker = null;
private void MyButton_Click(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10000000; i++)
{
DoIt();
}
}
Then you can use that to cancel the long operation:
private BackgroundWorker worker = null;
private void MyButton_Click(object sender, EventArgs e)
{
if (worker == null)
{
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
}
else
{
worker.CancelAsync();
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
worker = null;
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (worker != null)
{
for (int i = 0; i < 10000000 && !worker.CancellationPending; i++)
{
DoIt();
}
}
}