-
-
Save liorksh/f3272417367aacfa2ad60fabc0489d97 to your computer and use it in GitHub Desktop.
Exemplify the usage of Task.ContinueWith
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
[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