I have a slow proc gen function that runs when a user changes any parameters.
If a parameter is changed before it has completed, I want it to cancel the task and start a new one.
Currently I have it checking if a cancellation token is null, and if not requesting a cancellation before launching a new task.
public static async void Generate(myInputParams Input)
{
SectorData myData;
if (_tokenSource != null)
{
_tokenSource.Cancel();
_tokenSource.Dispose();
}
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
myData = await Task.Run(() => SlowFunction(Input, token));
// do stuff with new data
}
This does work but it seems to me that it's possible for the new task to be run before the cleanup code and cancelation in the previous one have completed.
Is there a way I can guarantee the previous task is done before starting the new one?
EDIT: I had forgotten to pass the token to the SlowFunction in this example. That wasn't the issue with my real one it just happened when I was renaming things to make it easier to read.
Also typos