Skip to content

Instantly share code, notes, and snippets.

@liorksh

liorksh/Task Continuation.cs Secret

Created Apr 26, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.