I have a method call within the background worker doWork event like this.
try
{
classname.method(argument, argument, argument);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
how i can implement a cancel to background worker. where to check for cancel pending. if i write the code like this
while (!bgworker.CancellationPending)
{
try
{
classname.method(argument, argument, argument);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
if (bgworker.CancellationPending
e.Cancel = true;
then it keeps running again and again until the cancel button (bgworker.CancelAsync()) is not pressed. please help me i am new to C#. i search a lot but find examples which have loops in doWork, but i have method call.
Loading
Benjamin ScharbachPosted Oct 14, 2017, 2:30 PM
Danatas GerviPosted Aug 31, 2009, 1:02 PM
Something like this:
namespace BackGrWorkCancel
{
public partial class Form1 : Form
{
Classname m_worker;
public Form1()
{
InitializeComponent();
m_worker = new Classname();
backgroundWorker1.RunWorkerAsync();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
m_worker.Method(backgroundWorker1);
}
}
public class Classname
{
//public bool ContinueWork = true;
public void Method(BackgroundWorker initiator)
{
//while (ContinueWork)
while(initiator.CancellationPending == false)
{
System.Threading.Thread.Sleep(2000);
Form tempForm = new Form();
tempForm.Show();
}
}
}
}