Task<TResult> Construtores
Definição
Inicializa um novo objeto Task<TResult>.Initializes a new Task<TResult> object.
Sobrecargas
| Task<TResult>(Func<TResult>) |
Inicializa um novo Task<TResult> com a função especificada.Initializes a new Task<TResult> with the specified function. |
| Task<TResult>(Func<Object,TResult>, Object) |
Inicializa um novo Task<TResult> com a função e o estado especificados.Initializes a new Task<TResult> with the specified function and state. |
| Task<TResult>(Func<TResult>, CancellationToken) |
Inicializa um novo Task<TResult> com a função especificada.Initializes a new Task<TResult> with the specified function. |
| Task<TResult>(Func<TResult>, TaskCreationOptions) |
Inicializa um novo Task<TResult> com a função especificada e opções de criação.Initializes a new Task<TResult> with the specified function and creation options. |
| Task<TResult>(Func<Object,TResult>, Object, CancellationToken) |
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options. |
| Task<TResult>(Func<Object,TResult>, Object, TaskCreationOptions) |
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options. |
| Task<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions) |
Inicializa um novo Task<TResult> com a função especificada e opções de criação.Initializes a new Task<TResult> with the specified function and creation options. |
| Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions) |
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options. |
Task<TResult>(Func<TResult>)
Inicializa um novo Task<TResult> com a função especificada.Initializes a new Task<TResult> with the specified function.
public:
Task(Func<TResult> ^ function);
public Task (Func<TResult> function);
new System.Threading.Tasks.Task<'Result> : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult))
Parâmetros
- function
- Func<TResult>
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
Exceções
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Exemplos
O exemplo a seguir conta o número aproximado de palavras em arquivos de texto que representam os livros publicados.The following example counts the approximate number of words in text files that represent published books. Cada tarefa é responsável por abrir um arquivo, ler todo o conteúdo de forma assíncrona e calcular a contagem de palavras usando uma expressão regular.Each task is responsible for opening a file, reading its entire contents asynchronously, and calculating the word count by using a regular expression. O Task.WaitAll(Task[]) método é chamado para garantir que todas as tarefas tenham sido concluídas antes de exibir a contagem de palavras de cada livro para o console.The Task.WaitAll(Task[]) method is called to ensure that all tasks have completed before displaying the word count of each book to the console.
A instanciação de objeto é separada da execução de objeto neste exemplo para que o exemplo possa garantir que cada arquivo exista.Object instantiation is separated from object execution in this example so that the example can ensure that each file exists. Se não tiverem, ele exibirá o nome do arquivo ausente.If they do not, it displays the name of the missing file. Caso contrário, ele chamará o Task.Start método para iniciar cada tarefa.Otherwise, it calls the Task.Start method to launch each task.
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
string pattern = @"\p{P}*\s+";
string[] titles = { "Sister Carrie", "The Financier" };
Task<int>[] tasks = new Task<int>[titles.Length];
for (int ctr = 0; ctr < titles.Length; ctr++) {
string s = titles[ctr];
tasks[ctr] = new Task<int>( () => {
// Number of words.
int nWords = 0;
// Create filename from title.
string fn = s + ".txt";
StreamReader sr = new StreamReader(fn);
string input = sr.ReadToEndAsync().Result;
sr.Close();
nWords = Regex.Matches(input, pattern).Count;
return nWords;
} );
}
// Ensure files exist before launching tasks.
bool allExist = true;
foreach (var title in titles) {
string fn = title + ".txt";
if (! File.Exists(fn)) {
allExist = false;
Console.WriteLine("Cannot find '{0}'", fn);
break;
}
}
// Launch tasks
if (allExist) {
foreach (var t in tasks)
t.Start();
await Task.WhenAll(tasks);
Console.WriteLine("Word Counts:\n");
for (int ctr = 0; ctr < titles.Length; ctr++)
Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
}
}
}
// The example displays the following output:
// Sister Carrie: 159,374 words
// The Financier: 196,362 words
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim pattern As String = "\p{P}*\s+"
Dim titles() As String = { "Sister Carrie",
"The Financier" }
Dim tasks(titles.Length - 1) As Task(Of Integer)
For ctr As Integer = 0 To titles.Length - 1
Dim s As String = titles(ctr)
tasks(ctr) = New Task(Of Integer)( Function()
' Number of words.
Dim nWords As Integer = 0
' Create filename from title.
Dim fn As String = s + ".txt"
Dim sr As New StreamReader(fn)
Dim input As String = sr.ReadToEndAsync().Result
sr.Close()
nWords = Regex.Matches(input, pattern).Count
Return nWords
End Function)
Next
' Ensure files exist before launching tasks.
Dim allExist As Boolean = True
For Each title In titles
Dim fn As String = title + ".txt"
If Not File.Exists(fn) Then
allExist = false
Console.WriteLine("Cannot find '{0}'", fn)
Exit For
End If
Next
' Launch tasks
If allExist Then
For Each t in tasks
t.Start()
Next
Task.WaitAll(tasks)
Console.WriteLine("Word Counts:")
Console.WriteLine()
For ctr As Integer = 0 To titles.Length - 1
Console.WriteLine("{0}: {1,10:N0} words", titles(ctr), tasks(ctr).Result)
Next
End If
End Sub
End Module
' The example displays the following output:
' Sister Carrie: 159,374 words
' The Financier: 196,362 words
O padrão de expressão regular \p{P}*\s+ corresponde a zero, um ou mais caracteres de Pontuação seguidos por um ou mais caracteres de espaço em branco.The regular expression pattern \p{P}*\s+ matches zero, one, or more punctuation characters followed by one or more white-space characters. Ele pressupõe que o número total de correspondências é igual à contagem aproximada de palavras.It assumes that the total number of matches equals the approximate word count.
Comentários
Esse construtor só deve ser usado em cenários avançados em que é necessário que a criação e o início da tarefa sejam separados.This constructor should only be used in advanced scenarios where it is required that the creation and starting of the task is separated.
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando os Task.Run<TResult>(Func<TResult>) métodos estáticos e TaskFactory<TResult>.StartNew(Func<TResult>) .Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static Task.Run<TResult>(Func<TResult>) and TaskFactory<TResult>.StartNew(Func<TResult>) methods.
Se uma tarefa sem nenhuma ação for necessária apenas para que o consumidor de uma API tenha algo a esperar, TaskCompletionSource<TResult> deve ser usado um.If a task with no action is needed just for the consumer of an API to have something to await, a TaskCompletionSource<TResult> should be used.
Aplica-se a
Task<TResult>(Func<Object,TResult>, Object)
Inicializa um novo Task<TResult> com a função e o estado especificados.Initializes a new Task<TResult> with the specified function and state.
public:
Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state);
public Task (Func<object,TResult> function, object state);
public Task (Func<object?,TResult> function, object? state);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object)
Parâmetros
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- state
- Object
Um objeto que representa dados a serem usados pela ação.An object representing data to be used by the action.
Exceções
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<TResult>, CancellationToken)
Inicializa um novo Task<TResult> com a função especificada.Initializes a new Task<TResult> with the specified function.
public:
Task(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public Task (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), cancellationToken As CancellationToken)
Parâmetros
- function
- Func<TResult>
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- cancellationToken
- CancellationToken
O CancellationToken a ser atribuído a essa tarefa.The CancellationToken to be assigned to this task.
Exceções
O CancellationTokenSource que criou cancellationToken já foi descartado.The CancellationTokenSource that created cancellationToken has already been disposed.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando os Task.Run<TResult>(Func<TResult>, CancellationToken) métodos estáticos e TaskFactory<TResult>.StartNew(Func<TResult>, CancellationToken) .Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static Task.Run<TResult>(Func<TResult>, CancellationToken) and TaskFactory<TResult>.StartNew(Func<TResult>, CancellationToken) methods. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<TResult>, TaskCreationOptions)
Inicializa um novo Task<TResult> com a função especificada e opções de criação.Initializes a new Task<TResult> with the specified function and creation options.
public:
Task(Func<TResult> ^ function, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<TResult> function, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), creationOptions As TaskCreationOptions)
Parâmetros
- function
- Func<TResult>
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- creationOptions
- TaskCreationOptions
O TaskCreationOptions usado para personalizar o comportamento da tarefa.The TaskCreationOptions used to customize the task's behavior.
Exceções
O argumento creationOptions especifica um valor inválido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory<TResult>.StartNew(Func<TResult>, TaskCreationOptions) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<TResult>, TaskCreationOptions) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<Object,TResult>, Object, CancellationToken)
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options.
public:
Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public Task (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken);
public Task (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object, cancellationToken As CancellationToken)
Parâmetros
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- state
- Object
Um objeto que representa dados a serem usados pela função.An object representing data to be used by the function.
- cancellationToken
- CancellationToken
O CancellationToken a ser atribuído a essa nova tarefa.The CancellationToken to be assigned to the new task.
Exceções
O CancellationTokenSource que criou cancellationToken já foi descartado.The CancellationTokenSource that created cancellationToken has already been disposed.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options.
public:
Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<object,TResult> function, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Func<object?,TResult> function, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object, creationOptions As TaskCreationOptions)
Parâmetros
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- state
- Object
Um objeto que representa dados a serem usados pela função.An object representing data to be used by the function.
- creationOptions
- TaskCreationOptions
O TaskCreationOptions usado para personalizar o comportamento da tarefa.The TaskCreationOptions used to customize the task's behavior.
Exceções
O argumento creationOptions especifica um valor inválido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, TaskCreationOptions) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, TaskCreationOptions) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions)
Inicializa um novo Task<TResult> com a função especificada e opções de criação.Initializes a new Task<TResult> with the specified function and creation options.
public:
Task(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<TResult> function, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<'Result> * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of TResult), cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)
Parâmetros
- function
- Func<TResult>
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído a nova tarefa.The CancellationToken that will be assigned to the new task.
- creationOptions
- TaskCreationOptions
O TaskCreationOptions usado para personalizar o comportamento da tarefa.The TaskCreationOptions used to customize the task's behavior.
Exceções
O CancellationTokenSource que criou cancellationToken já foi descartado.The CancellationTokenSource that created cancellationToken has already been disposed.
O argumento creationOptions especifica um valor inválido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory.StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory.StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
Aplica-se a
Task<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions)
Inicializa um novo Task<TResult> com a ação, o estado e as opções especificados.Initializes a new Task<TResult> with the specified action, state, and options.
public:
Task(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Func<object?,TResult> function, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task<'Result> : Func<obj, 'Result> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Sub New (function As Func(Of Object, TResult), state As Object, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)
Parâmetros
O delegado que representa o código a ser executado na tarefa.The delegate that represents the code to execute in the task. Quando a função for concluída, a propriedade Result da tarefa será definida para retornar o valor do resultado da função.When the function has completed, the task's Result property will be set to return the result value of the function.
- state
- Object
Um objeto que representa dados a serem usados pela função.An object representing data to be used by the function.
- cancellationToken
- CancellationToken
O CancellationToken a ser atribuído a essa nova tarefa.The CancellationToken to be assigned to the new task.
- creationOptions
- TaskCreationOptions
O TaskCreationOptions usado para personalizar o comportamento da tarefa.The TaskCreationOptions used to customize the task's behavior.
Exceções
O CancellationTokenSource que criou cancellationToken já foi descartado.The CancellationTokenSource that created cancellationToken has already been disposed.
O argumento creationOptions especifica um valor inválido para TaskCreationOptions.The creationOptions argument specifies an invalid value for TaskCreationOptions.
O argumento function é null.The function argument is null.
O argumento function é null.The function argument is null.
Comentários
Em vez de chamar esse construtor, a maneira mais comum de instanciar um Task<TResult> objeto e iniciar uma tarefa é chamando o TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) método estático.Rather than calling this constructor, the most common way to instantiate a Task<TResult> object and launch a task is by calling the static TaskFactory<TResult>.StartNew(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) method. A única vantagem oferecida por esse construtor é que ele permite que a instanciação de objeto seja separada da invocação de tarefa.The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.