TaskBlocksWhile Method (FuncTaskBoolean, FuncTask) |
Namespace: Rackspace.Threading
Exception | Condition |
---|---|
ArgumentNullException |
If condition is . -or- If body is . |
InvalidOperationException |
If condition returns . -or- If body returns . |
This code implements support for the following construct without requiring the use of /.
while (await condition().ConfigureAwait(false)) { await body().ConfigureAwait(false); }
The following example shows a basic "while" loop implemented using this building block.
public Task While() { Stack<int> workList = new Stack<int>(new[] { 3, 5, 7 }); return TaskBlocks.While( () => HasItemsAsync(workList), () => ProcessWorkItemAsync(workList.Pop())); } private Task<bool> HasItemsAsync(Stack<int> workList) { // this would typically perform an asynchronous operation to test // some condition of the input parameter(s) return CompletedTask.FromResult(workList.Count > 0); } private Task ProcessWorkItemAsync(int item) { // this would typically perform an asynchronous operation on the // work item return CompletedTask.Default; }
For reference, the following example demonstrates a (nearly) equivalent implementation of this behavior using the / operators.
public async Task WhileAsyncAwait() { Stack<int> workList = new Stack<int>(new[] { 3, 5, 7 }); while (await HasItemsAsyncAwait(workList)) { await ProcessWorkItemAsyncAwait(workList.Pop()); } } private async Task<bool> HasItemsAsyncAwait(Stack<int> workList) { // this would typically perform an asynchronous operation to test // some condition of the input parameter(s) return workList.Count > 0; } private async Task ProcessWorkItemAsyncAwait(int item) { // this would typically perform an asynchronous operation on the // work item }