Click or drag to resize
TaskBlocksWhile Method (FuncBoolean, 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<bool> condition,
	Func<Task> body
)

Parameters

condition
Type: SystemFuncBoolean
A function which evaluates the condition of the asynchronous while loop.
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 body returns .

Remarks

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

C#
while (condition())
{
    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(
        () => workList.Count > 0,
        () => ProcessWorkItemAsync(workList.Pop()));
}

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 (workList.Count > 0)
    {
        await ProcessWorkItemAsyncAwait(workList.Pop());
    }
}

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