Created
April 22, 2019 17:18
-
-
Save felipeslongo/264930c35a1df9a99e9b581f36accde5 to your computer and use it in GitHub Desktop.
SelfCancellingAndRestartingTask Pattern Example: https://stackoverflow.com/questions/18999827/a-pattern-for-self-cancelling-and-restarting-task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Task pendingTask = null; // pending session | |
CancellationTokenSource cts = null; // CTS for pending session | |
// SpellcheckAsync is called by the client app on the UI thread | |
public async Task<bool> SpellcheckAsync(CancellationToken token) | |
{ | |
// SpellcheckAsync can be re-entered | |
var previousCts = this.cts; | |
var newCts = CancellationTokenSource.CreateLinkedTokenSource(token); | |
this.cts = newCts; | |
if (previousCts != null) | |
{ | |
// cancel the previous session and wait for its termination | |
previousCts.Cancel(); | |
try { await this.pendingTask; } catch { } | |
} | |
newCts.Token.ThrowIfCancellationRequested(); | |
this.pendingTask = SpellcheckAsyncHelper(newCts.Token); | |
return await this.pendingTask; | |
} | |
// the actual task logic | |
async Task<bool> SpellcheckAsyncHelper(CancellationToken token) | |
{ | |
// do the work (pretty much IO-bound) | |
using (...) | |
{ | |
bool doMore = true; | |
while (doMore) | |
{ | |
token.ThrowIfCancellationRequested(); | |
await Task.Delay(500); // placeholder to call the provider | |
} | |
return doMore; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment