Hello @Sudip Bhatt
You can use BackgroundWorker.CancelAsync and the BackGroundWorker is scope is public.
Alternate solution is to consider using a cancellation token and discard using a BackGroundWorker. If open to this read on.
User Control
That iterates a for/next and when a cancel request is received cancel the code in the for.
Note
async Task.Delay would be set to 1 rather than 1000 while if set to 1 in this code you would not have time to click the cancel button.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CancellationToken
{
public partial class ControlDemo : UserControl
{
public System.Threading.CancellationToken _cancellationToken;
public ControlDemo()
{
InitializeComponent();
}
public async void DoSomething()
{
try
{
for (int index = 0; index < 5000; index++)
{
Console.WriteLine(index);
await Task.Delay(1000, _cancellationToken);
if (_cancellationToken.IsCancellationRequested)
_cancellationToken.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException oce)
{
Console.WriteLine("User cancelled");
}
catch (Exception ex)
{
// TODO
}
}
private void button1_Click(object sender, EventArgs e)
{
DoSomething();
}
}
}
Form code
Place the following in the form e.g. first line in the form
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
Add a button for demo purposes, your code may want this in say the form load or shown event.
private void RunDemobutton_Click(object sender, EventArgs e)
{
if (_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Dispose();
_cancellationTokenSource = new CancellationTokenSource();
}
controlDemo1._cancellationToken = _cancellationTokenSource.Token;
}
Add a button for cancelation with the following line.
_cancellationTokenSource.Cancel();