Skip to content

Instantly share code, notes, and snippets.


liorksh/Task Continuation.cs Secret

Created Apr 26, 2020
What would you like to do?
Exemplify the usage of Task.ContinueWith
[InlineData(155, 34)]
public void TasksContinueWith(int booksAllowance, int booksToWithdraw)
// Initiate a library account object
LibraryAccount libraryAccount = new LibraryAccount(booksAllowance);
Task<int> task = Task.Factory.StartNew<int>(() =>{
// The first task withdraws books
return libraryAccount.BorrowedBooksCount;
.ContinueWith<int>((prevTask) => {
// Fetching the result from the previous task
int booksInventory = prevTask.Result;
Trace.WriteLine($"Current books inventory count {booksInventory}");
// Return the books back to the library
return libraryAccount.BorrowedBooksCount;
}, // Set the conditions when to continue the subsequent task
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.NotOnCanceled |
// Wait for the task to end before continuing the main thread.
// The actual number of books should remain the same
Assert.Equal(task.Result, booksAllowance);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.