Reputation: 199
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
Upvotes: 1
Views: 349
Reputation: 457302
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?
Sure: save the task in a variable (just like you're currently doing with _tokenSource
), and await
it before starting the new task. You'll probably want to await
it in a try
/finally
block and ignore errors, at least if they're OperationCanceledException
kinds of errors.
I'm assuming that this is a single-threaded UI context, where Generate
is an event handler called on the UI thread. Otherwise, your class-level variables will need to be protected by mutexes and the async void
should be removed.
Upvotes: 1