Skip to content

Instantly share code, notes, and snippets.

@liorksh
Created April 26, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liorksh/f3272417367aacfa2ad60fabc0489d97 to your computer and use it in GitHub Desktop.
Save liorksh/f3272417367aacfa2ad60fabc0489d97 to your computer and use it in GitHub Desktop.
Exemplify the usage of Task.ContinueWith
[Theory]
[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
libraryAccount.WithdrawBooks(booksToWithdraw);
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
libraryAccount.ReturnBooks(booksToWithdraw);
return libraryAccount.BorrowedBooksCount;
}, // Set the conditions when to continue the subsequent task
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.NotOnCanceled |
TaskContinuationOptions.OnlyOnRanToCompletion);
// Wait for the task to end before continuing the main thread.
task.Wait();
// 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