I have 2 checkboxes. Checkbox_toggle
, when checked, will initiate a toggle sequence. This toggle sequence will check and uncheck Checkbox_control
with a timer/delay.
I want that to keep looping as long as Checkbox_toggle is checked. However, Thread.Sleep won't work for my purposes as I need the rest of the program to continue running. I looked into BackgroundWorker
and I can't quite find an example/I don't understand it well enough to apply it to my program. I'm using .NET 4.0 so I can't use Task.Delay
.
I know with BackgroundWorker
there's the ProgressChanged
event that can be used to update the UI, but I'm not really sure how I would be able to use that for my application. I'm also open to another solution that isn't BackgroundWorker
.
I tried using this .NET 4.0 implementation of Task.Delay, but it's not working how I'd like. It runs through all of that but the delay doesn't actually delay the loop
public static System.Threading.Tasks.Task Delay(double milliseconds)
{
var tcs = new TaskCompletionSource<bool>();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += (obj, args) =>
{
tcs.TrySetResult(true);
};
timer.Interval = milliseconds;
timer.AutoReset = false;
timer.Start();
return tcs.Task;
}
private void Checkbox_toggle_CheckedChanged(object sender, EventArgs e)
{
while (Checkbox_toggle.Checked == true)
{
Checkbox_control.Checked = true;
Delay(1000);
Checkbox_control.Checked = false;
Delay(1000);
}
}
Task delay event found here: https://stackoverflow.com/a/15342256/8407531
My actual question: How can I toggle a checkbox on a timer without using Thread.Sleep, or how can I offset it to another thread? If possible, this delay needs to be adjustable from the other thread.