Home

TaskWhenAny

Task.WhenAny is a static method in the .NET framework (System.Threading.Tasks) that implements a race among multiple tasks. It returns a task that completes as soon as any one of the supplied tasks completes. The result is the completed task itself, not its value.

Overloads and return types include non-generic and generic forms. For non-generic tasks, the method returns Task<Task>,

Behavior and semantics: WhenAny completes, it does not guarantee that the first completed task is successful;

Usage patterns include racing multiple asynchronous operations to proceed with the quickest result, implementing timeouts, or

See also: Task.WhenAll, cancellation and timeouts in asynchronous programming, and patterns for coordinating multiple tasks in

with
overloads
such
as
Task.WhenAny(params
Task[]
tasks)
and
Task.WhenAny(IEnumerable<Task>
tasks).
For
generic
tasks,
there
are
overloads
like
Task.WhenAny<TResult>(IEnumerable<Task<TResult>>
tasks)
which
return
Task<Task<TResult>>.
In
all
cases,
the
outer
task
completes
when
any
input
task
completes,
and
the
inner
task
is
the
actual
completed
task.
it
may
be
ran
into
a
faulted
or
canceled
state.
The
outer
task
completes
as
soon
as
the
first
input
task
finishes,
regardless
of
outcome.
To
observe
the
result
or
exception,
you
typically
await
the
inner
task
(for
example,
after
awaiting
the
outer
task
you
await
the
resulting
completed
task).
It
does
not
cancel
or
otherwise
terminate
the
remaining
tasks
automatically;
cancellation
must
be
handled
separately
through
cancellation
tokens
or
manual
logic.
coordinating
asynchronous
work
where
the
earliest
completion
dictates
subsequent
steps.
It
is
often
used
in
conjunction
with
Task.WhenAll
or
with
explicit
cancellation
to
manage
remaining
tasks
after
the
first
completion.
the
.NET
Task
Parallel
Library.