There is data processing in my program that can take quite a while. Essentially it's a loop that reads data from file in small segments and applies it to a data model step by step. Simplified code looks like this:
public void LoadFromFile()
{
while (this.playbackFile.HasMoreData)
{
this.ProcessData(this.playbackFile); // Process a single data segment
}
}
To keep my WPF UI responsive I wrapped it into a Task like this:
public Task LoadFile()
{
return Task.Run(() => this.LoadFromFile());
}
And then simply use it when a button is clicked to start:
await this.playbackController.LoadFile();
Now what I want to do is to add controls for this operation: pause/resume, step, stop. I also want an ability to control execution speed, for example, to slow down processing to simulate real-time data input by calculating timestamps difference between previous and next data segments and increasing the time it takes to process next segment according to that (essentially causing a delay with an interval that changes between each segment). When I think about it I want to implement something that could control my task like this:
WaitFor(x); // Delay for x ms to simulate speed decrease
WaitFor(-1); // Indefinite delay on pause; waits until resume is signaled
While researching my options I found recommendations to use AsyncManualResetEvent
or PauseToken
to control pause/resume, though I am not sure how I can integrate delay with that.
Instead of having one large task it would make sense for me to make each segment processing a separate task (actually, it would be preferred to pause between data segments processing, not in the middle of operation, and stepping would require it anyway) and then I could possibly control each one of them with something like Task.Delay
, but I am not sure if it's a good idea and if it allows me to do pause/resume.
I would be grateful if someone could point me in the right direction with this.