C
C#2y ago
BElluu

❔ How to disable background worker?

Hi, I need to do something in background when state is true and stop when state is false. I changing state by button. If I press button, state is true unit I press button again. I set WorkerSupportsCancellation on true. When I press button again, I have all the time TEST in console. Any idea?
private void Start_Click(object sender, EventArgs e)
{
if (started)
{
StartButton.Text = "Start";
started = false;
backgroundWorker1.CancelAsync();
InitCheckLocalTimer().Stop();
InitCheckLocalTimer().Dispose();
}
else
{
StartButton.Text = "Stop";
started = true;
InitCheckLocalTimer().Start();
}
}

private void CheckLocalTimer(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
if (!backgroundWorker1.CancellationPending && !e.Cancel)
{
Console.WriteLine("TEST")
}
else
{
e.Cancel = true;
}
}
private void Start_Click(object sender, EventArgs e)
{
if (started)
{
StartButton.Text = "Start";
started = false;
backgroundWorker1.CancelAsync();
InitCheckLocalTimer().Stop();
InitCheckLocalTimer().Dispose();
}
else
{
StartButton.Text = "Stop";
started = true;
InitCheckLocalTimer().Start();
}
}

private void CheckLocalTimer(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
if (!backgroundWorker1.CancellationPending && !e.Cancel)
{
Console.WriteLine("TEST")
}
else
{
e.Cancel = true;
}
}
2 Replies
Angius
Angius2y ago
You don't await any of your async methods. You don't even run them in a blocking manner. Everything is fire and forget. I'm not 100% sure that's the issue, but very much seems like it might be
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server