Click or drag to resize
TaskBlocksWhile Method (FuncTaskBoolean, FuncTask)
Provides support for a conditional "while" loop in asynchronous code, without requiring the use of /.

Namespace: Rackspace.Threading
Assembly: Rackspace.Threading (in Rackspace.Threading.dll) Version: 2.1.0-beta1
Syntax
public static Task While(
	Func<Task<bool>> condition,
	Func<Task> body
)

Parameters

condition
Type: SystemFuncTaskBoolean
A function which returns a Task representing the asynchronous evaluation of the while condition.
body
Type: SystemFuncTask
A function which returns a Task representing one iteration of the body of the while loop.

Return Value

Type: Task
A Task representing the asynchronous operation.
Exceptions
ExceptionCondition
ArgumentNullException

If condition is .

-or-

If body is .

InvalidOperationException

If condition returns .

-or-

If body returns .

Remarks

This code implements support for the following construct without requiring the use of /.

C#
while (await condition().ConfigureAwait(false))
{
    await body().ConfigureAwait(false);
}
Examples

The following example shows a basic "while" loop implemented using this building block.

C#
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.

C#
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
}
Version Information

.NET for Windows Store apps

Supported in: Windows 8

.NET Framework

Supported in: 4.5, 4.0, 3.5

Portable Class Library

Supported in: Portable Class Library (Legacy), Portable Class Library

Threading Library

Supported in: 2.1, 2.0, 1.1, 1.0
See Also