How to handle case, where user might hit the button, which invokes long running async operation, multiple time.
My idea was first check if the async operation is running, cancel it and fire it again.
So far I have tried to build this kind of functionality using CancellationTokenSource, but it is not working as expected. Some times there is two async operations running, so the "old" async oprations is not cancelled yet when I start new one and this mixes up the resul handling.
Any suggestions or examples how to handle this kind of case?
public async void Draw()
{
bool result = false;
if (this.cts == null)
{
this.cts = new CancellationTokenSource();
try
{
result = await this.DrawContent(this.TimePeriod, this.cts.Token);
}
catch (Exception ex)
{}
finally
{
this.cts = null;
}
}
else
{
this.cts.Cancel();
this.cts = new CancellationTokenSource();
try
{
result = await this.DrawContent(this.TimePeriod, this.cts.Token);
}
catch (Exception ex)
{}
finally
{
this.cts = null;
}
}
}
EDIT: In the end, I think it is not bad that there is two async operations running in short time (when the new is fired but the old one is not yet cancelled).
The real problem here is how I display the progress for enduser. As when the old async operation ends, it hides the progress indicator from enduser but the newly fired async operation is still running.
EDIT2: Inside DrawContent(...) I use ThrowIfCancellationRequested, so cancelling the running task seems to work ok.
About progress display. When the Draw() is called, I set loading indicator visible and when this method ends, I hide loading indicator. So now when the previous async operation is cancelled after I start new one, my loading indicator is set hidden. How should I keep track if there is another async method still running when the "old" one ends.