Класс task (среда выполнения с параллелизмом)task Class (Concurrency Runtime)
Класс task
библиотеки параллельных шаблонов (PPL).The Parallel Patterns Library (PPL) task
class. task
Объект представляет работу, которая может быть выполнена асинхронно и параллельно с другими задачами, а также параллелизмом, созданными параллельными алгоритмами в среда выполнения с параллелизмом.A task
object represents work that can be executed asynchronously and concurrently with other tasks and parallel work produced by parallel algorithms in the Concurrency Runtime. При успешном завершении он выводи результат типа _ResultType
.It produces a result of type _ResultType
on successful completion. Задачи типа task<void>
никакого результата не дают.Tasks of type task<void>
produce no result. Задачи можно ожидать и отменять независимо от других задач.A task can be waited upon and canceled independently of other tasks. Он также может состоять из других задач, использующих шаблоны продолжения () then
и объединения () when_all
и Choice ( when_any
).It can also be composed with other tasks using continuations( then
), and join( when_all
) and choice( when_any
) patterns. Когда объект Task назначается новой переменной, поведение состоит в том, что, иными std::shared_ptr
словами, оба объекта представляют одну и ту же базовую задачу.When a task object is assigned to a new variable, the behavior is that of std::shared_ptr
; in other words, both objects represent the same underlying task.
СинтаксисSyntax
template <>
class task<void>;
template<typename _ResultType>
class task;
ПараметрыParameters
_ResultType_ResultType
Тип результата, который создает задача.The type of the result that the task produces.
ЭлементыMembers
Общедоступные определения типовPublic Typedefs
ИмяName | ОписаниеDescription |
---|---|
result_type |
Тип результата, выводимого объектом этого класса.The type of the result an object of this class produces. |
Открытые конструкторыPublic Constructors
nameName | ОписаниеDescription |
---|---|
задачиtask | Перегружен.Overloaded. Формирует объект task .Constructs a task object. |
Открытые методыPublic Methods
nameName | ОписаниеDescription |
---|---|
getget | Перегружен.Overloaded. Возвращает результат, созданный этой задачей.Returns the result this task produced. Если задача не находится в конечном состоянии, вызов get будет ожидать завершения задачи.If the task is not in a terminal state, a call to get will wait for the task to finish. Этот метод не возвращает значение при вызове в задаче с параметром result_type void .This method does not return a value when called on a task with a result_type of void . |
is_apartment_awareis_apartment_aware | Определяет, распаковывает ли задача интерфейс среды выполнения Windows IAsyncInfo или происходит от такой задачи.Determines whether the task unwraps a Windows Runtime IAsyncInfo interface or is descended from such a task. |
is_doneis_done | Определяет, завершена ли задача.Determines if the task is completed. |
планировщикаscheduler | Возвращает планировщик для этой задачиReturns the scheduler for this task |
этогоthen | Перегружен.Overloaded. Добавляет задачу продолжения к этой задаче.Adds a continuation task to this task. |
ожиданияwait | Ожидает, когда эта задача достигнет конечного состояния.Waits for this task to reach a terminal state. У wait существует возможность выполнения задачи встроенным образом, если все зависимости задач удовлетворены, и она еще не взята для выполнения фоновым рабочим процессом.It is possible for wait to execute the task inline, if all of the tasks dependencies are satisfied, and it has not already been picked up for execution by a background worker. |
Открытые операторыPublic Operators
ИмяName | ОписаниеDescription |
---|---|
operator! =operator!= | Перегружен.Overloaded. Определяет, представляют ли два объекта task различные внутренние задачи.Determines whether two task objects represent different internal tasks. |
Оператор =operator= | Перегружен.Overloaded. Заменяет содержимое одного объекта task другим.Replaces the contents of one task object with another. |
Оператор = =operator== | Перегружен.Overloaded. Определяет, представляют ли два объекта task одну и ту же внутреннюю задачу.Determines whether two task objects represent the same internal task. |
КомментарииRemarks
Дополнительные сведения см. в разделе параллелизм задач.For more information, see Task Parallelism.
Иерархия наследованияInheritance Hierarchy
task
ТребованияRequirements
Заголовок: из ppltasks. hHeader: ppltasks.h
Пространство имен: параллелизмNamespace: concurrency
Получитьget
Возвращает результат, созданный этой задачей.Returns the result this task produced. Если задача не находится в конечном состоянии, вызов get
будет ожидать завершения задачи.If the task is not in a terminal state, a call to get
will wait for the task to finish. Этот метод не возвращает значение при вызове в задаче с параметром result_type
void
.This method does not return a value when called on a task with a result_type
of void
.
_ResultType get() const;
void get() const;
Возвращаемое значениеReturn Value
Результат задачи.The result of the task.
КомментарииRemarks
Если задача отменена, вызов выдаст get
исключение task_canceled .If the task is canceled, a call to get
will throw a task_canceled exception. Если задача встретила другое исключение или исключение было распространено на нее из предшествующей задачи, вызов get
создаст это исключение.If the task encountered an different exception or an exception was propagated to it from an antecedent task, a call to get
will throw that exception.
Важно!
В приложении универсальная платформа Windows (UWP) не вызывайте Concurrency:: Task:: wait или get
( wait
Calls get
) в коде, который выполняется в потоке пользовательского интерфейса.In a Universal Windows Platform (UWP) app, do not call concurrency::task::wait or get
( wait
calls get
) in code that runs on the user-interface thread. В противном случае среда выполнения создает Concurrency:: invalid_operation , так как эти методы блокируют текущий поток и могут привести к тому, что приложение перестанет отвечать на запросы.Otherwise, the runtime throws concurrency::invalid_operation because these methods block the current thread and can cause the app to become unresponsive. Однако можно вызвать get
метод, чтобы получить результат предшествующей задачи в продолжении на основе задачи, так как результат сразу же доступен.However, you can call the get
method to receive the result of the antecedent task in a task-based continuation because the result is immediately available.
is_apartment_awareis_apartment_aware
Определяет, распаковывает ли задача интерфейс среды выполнения Windows IAsyncInfo
или происходит от такой задачи.Determines whether the task unwraps a Windows Runtime IAsyncInfo
interface or is descended from such a task.
bool is_apartment_aware() const;
Возвращаемое значениеReturn Value
true
значение, если задача разворачивает IAsyncInfo
интерфейс или по убыванию от такой задачи; false
в противном случае —.true
if the task unwraps an IAsyncInfo
interface or is descended from such a task, false
otherwise.
Метод Task:: is_done (среда выполнения с параллелизмом)task::is_done Method (Concurrency Runtime)
Определяет, завершена ли задача.Determines if the task is completed.
bool is_done() const;
Возвращаемое значениеReturn Value
Значение true, если задача завершена; в противном случае — значение false.True if the task has completed, false otherwise.
КомментарииRemarks
Функция возвращает значение true, если задача завершена или отменена (с исключением пользователя или без него).The function returns true if the task is completed or canceled (with or without user exception).
operator! =operator!=
Определяет, представляют ли два объекта task
различные внутренние задачи.Determines whether two task
objects represent different internal tasks.
bool operator!= (const task<_ResultType>& _Rhs) const;
bool operator!= (const task<void>& _Rhs) const;
ПараметрыParameters
_Rhs_Rhs
Сравниваемая задача.The task to compare.
Возвращаемое значениеReturn Value
true
значение, если объекты ссылаются на разные базовые задачи, и false
в противном случае.true
if the objects refer to different underlying tasks, and false
otherwise.
Оператор =operator=
Заменяет содержимое одного объекта task
другим.Replaces the contents of one task
object with another.
task& operator= (const task& _Other);
task& operator= (task&& _Other);
ПараметрыParameters
_Other_Other
Исходный объект task
.The source task
object.
Возвращаемое значениеReturn Value
КомментарииRemarks
Поскольку task
действует как интеллектуальный указатель, после назначения копии эти объекты task
представляют ту же фактическую задачу, что и _Other
.As task
behaves like a smart pointer, after a copy assignment, this task
objects represents the same actual task as _Other
does.
Оператор = =operator==
Определяет, представляют ли два объекта task
одну и ту же внутреннюю задачу.Determines whether two task
objects represent the same internal task.
bool operator== (const task<_ResultType>& _Rhs) const;
bool operator== (const task<void>& _Rhs) const;
ПараметрыParameters
_Rhs_Rhs
Сравниваемая задача.The task to compare.
Возвращаемое значениеReturn Value
true
значение, если объекты ссылаются на одну и ту же базовую задачу, и false
в противном случае.true
if the objects refer to the same underlying task, and false
otherwise.
Метод Task:: Scheduler (среда выполнения с параллелизмом)task::scheduler Method (Concurrency Runtime)
Возвращает планировщик для этой задачиReturns the scheduler for this task
scheduler_ptr scheduler() const;
Возвращаемое значениеReturn Value
Указатель на планировщикA pointer to the scheduler
Задача task
Формирует объект task
.Constructs a task
object.
task();
template<typename T>
__declspec(
noinline) explicit task(T _Param);
template<typename T>
__declspec(
noinline) explicit task(T _Param, const task_options& _TaskOptions);
task(
const task& _Other);
task(
task&& _Other);
ПараметрыParameters
TT
Тип параметра, из которого будет создаваться задача.The type of the parameter from which the task is to be constructed.
_Param_Param
Параметр, из которого будет создаваться задача.The parameter from which the task is to be constructed. Это может быть лямбда, объект функции, task_completion_event<result_type>
объект или Windows:: Foundation:: иасинЦинфо, если вы используете задачи в приложении среда выполнения Windows.This could be a lambda, a function object, a task_completion_event<result_type>
object, or a Windows::Foundation::IAsyncInfo if you are using tasks in your Windows Runtime app. Лямбда-выражение или объект функции должен быть типом, эквивалентным std::function<X(void)>
, где X может быть переменной типа result_type
, task<result_type>
или Windows:: Foundation:: иасинЦинфо в приложениях среда выполнения Windows.The lambda or function object should be a type equivalent to std::function<X(void)>
, where X can be a variable of type result_type
, task<result_type>
, or a Windows::Foundation::IAsyncInfo in Windows Runtime apps.
_TaskOptions_TaskOptions
Параметры задачи включают токен отмены, планировщик и др.The task options include cancellation token, scheduler etc
_Other_Other
Исходный объект task
.The source task
object.
КомментарииRemarks
Конструктор по умолчанию для task
присутствует только для того, чтобы задачи могли использоваться внутри контейнеров.The default constructor for a task
is only present in order to allow tasks to be used within containers. Собранную задачу по умолчанию невозможно использовать до тех пор, пока ей не будет присвоена допустимая задача.A default constructed task cannot be used until you assign a valid task to it. Такие методы get
, как wait
или, then
вызовут исключение invalid_argument при вызове для задачи, созданной по умолчанию.Methods such as get
, wait
or then
will throw an invalid_argument exception when called on a default constructed task.
Задача, которая создается из task_completion_event
, завершится (и ее продолжения будут запланированы), если событие завершения задачи установлено.A task that is created from a task_completion_event
will complete (and have its continuations scheduled) when the task completion event is set.
Версия конструктора, принимающего токен отмены, создает задачу, которую можно отменить с помощью cancellation_token_source
, из которого был получен токен.The version of the constructor that takes a cancellation token creates a task that can be canceled using the cancellation_token_source
the token was obtained from. Задачи, созданные без токена отмены, не могут быть отменены.Tasks created without a cancellation token are not cancelable.
Задачи, созданные из интерфейса Windows::Foundation::IAsyncInfo
или лямбда-выражения, которое возвращает интерфейс IAsyncInfo
, достигают своего конечного состояния при завершении вложенной асинхронной операции или действия среды выполнения Windows.Tasks created from a Windows::Foundation::IAsyncInfo
interface or a lambda that returns an IAsyncInfo
interface reach their terminal state when the enclosed Windows Runtime asynchronous operation or action completes. Аналогичным образом задачи, созданные из лямбда-выражения, возвращающего task<result_type>
состояние терминала, когда внутренняя задача достигает своего состояния терминала, а не при возврате лямбда-выражения.Similarly, tasks created from a lambda that returns a task<result_type>
reach their terminal state when the inner task reaches its terminal state, and not when the lambda returns.
task
ведет себя подобно интеллектуальному указателю, и ее можно безопасно передавать по значению.task
behaves like a smart pointer and is safe to pass around by value. К ней также может быть получен доступ несколькими потоками без необходимости использования блокировки.It can be accessed by multiple threads without the need for locks.
Перегрузки конструктора, которые принимают интерфейс Windows:: Foundation:: ИасинЦинфо или лямбда-выражение, возвращающие такой интерфейс, доступны только для среда выполнения Windows приложений.The constructor overloads that take a Windows::Foundation::IAsyncInfo interface or a lambda returning such an interface, are only available to Windows Runtime apps.
Дополнительные сведения см. в разделе параллелизм задач.For more information, see Task Parallelism.
этогоthen
Добавляет задачу продолжения к этой задаче.Adds a continuation task to this task.
template<typename _Function>
__declspec(
noinline) auto then(const _Function& _Func) const -> typename details::_ContinuationTypeTraits<_Function,
_ResultType>::_TaskOfType;
template<typename _Function>
__declspec(
noinline) auto then(const _Function& _Func,
const task_options& _TaskOptions) const -> typename details::_ContinuationTypeTraits<_Function,
_ResultType>::_TaskOfType;
template<typename _Function>
__declspec(
noinline) auto then(const _Function& _Func,
cancellation_token _CancellationToken,
task_continuation_context _ContinuationContext) const -> typename details::_ContinuationTypeTraits<_Function,
_ResultType>::_TaskOfType;
template<typename _Function>
__declspec(
noinline) auto then(const _Function& _Func,
const task_options& _TaskOptions = task_options()) const -> typename details::_ContinuationTypeTraits<_Function,
void>::_TaskOfType;
template<typename _Function>
__declspec(
noinline) auto then(const _Function& _Func,
cancellation_token _CancellationToken,
task_continuation_context _ContinuationContext) const -> typename details::_ContinuationTypeTraits<_Function,
void>::_TaskOfType;
ПараметрыParameters
_Function_Function
Тип объекта функции, который будет вызываться этой задачей.The type of the function object that will be invoked by this task.
_Func_Func
Функция продолжения, которая должна быть выполнена по завершении этой задачи.The continuation function to execute when this task completes. Эта функция продолжения должна принимать в качестве входных данных переменную типа result_type
или task<result_type>
, где result_type
— тип результата, который создает эта задача.This continuation function must take as input a variable of either result_type
or task<result_type>
, where result_type
is the type of the result this task produces.
_TaskOptions_TaskOptions
Параметры задачи включают токен отмены, планировщик и контекст продолжения.The task options include cancellation token, scheduler and continuation context. По умолчанию предыдущие 3 параметра наследуются от предшествующей задачиBy default the former 3 options are inherited from the antecedent task
_CancellationToken_CancellationToken
Токен отмены, который необходимо связать с задачей продолжения.The cancellation token to associate with the continuation task. Задача продолжения, созданная без токена отмены, унаследует токен своей предшествующей задачи.A continuation task that is created without a cancellation token will inherit the token of its antecedent task.
_ContinuationContext_ContinuationContext
Переменная, указывающая, где должно выполняться продолжение.A variable that specifies where the continuation should execute. Эта переменная полезна только при использовании в приложении UWP.This variable is only useful when used in a UWP app. Дополнительные сведения см. в разделе task_continuation_contextFor more information, see task_continuation_context
Возвращаемое значениеReturn Value
Вновь созданная задача продолжения.The newly created continuation task. Тип результата возвращаемой задачи определяется значением, возвращаемым _Func
.The result type of the returned task is determined by what _Func
returns.
КомментарииRemarks
Перегрузки then
, которые принимают лямбда-выражение или функтор, возвращающие интерфейс Windows:: Foundation:: иасинЦинфо, доступны только для Среда выполнения Windows приложений.The overloads of then
that take a lambda or functor that returns a Windows::Foundation::IAsyncInfo interface, are only available to Windows Runtime apps.
Дополнительные сведения об использовании продолжений задач для создания асинхронной работы см. в разделе параллелизм задач.For more information on how to use task continuations to compose asynchronous work, see Task Parallelism.
ожиданияwait
Ожидает, когда эта задача достигнет конечного состояния.Waits for this task to reach a terminal state. У wait
существует возможность выполнения задачи встроенным образом, если все зависимости задач удовлетворены, и она еще не взята для выполнения фоновым рабочим процессом.It is possible for wait
to execute the task inline, if all of the tasks dependencies are satisfied, and it has not already been picked up for execution by a background worker.
task_status wait() const;
Возвращаемое значениеReturn Value
Значение task_status
, которое может быть completed
или canceled
.A task_status
value which could be either completed
or canceled
. Если задача встретила исключение во время выполнения или исключение было распространено на нее из предшествующей задачи, wait
вызывает это исключение.If the task encountered an exception during execution, or an exception was propagated to it from an antecedent task, wait
will throw that exception.
КомментарииRemarks
Важно!
В приложении универсальная платформа Windows (UWP) не вызывайте wait
в коде, который выполняется в потоке пользовательского интерфейса.In a Universal Windows Platform (UWP) app, do not call wait
in code that runs on the user-interface thread. В противном случае среда выполнения создает concurrency::invalid_operation так как этот метод блокирует текущий поток и может вызвать зависание приложения.Otherwise, the runtime throws concurrency::invalid_operation because this method blocks the current thread and can cause the app to become unresponsive. Тем не менее можно вызвать метод concurrency::task::get для получения результата из предшествующей задачи в потоке задач.However, you can call the concurrency::task::get method to receive the result of the antecedent task in a task-based continuation.