Task.Wait Metoda
Definice
Přetížení
| Wait(Int32, CancellationToken) |
Čeká na Task dokončení provádění.Waits for the Task to complete execution. Čekání skončí, pokud uplyne časový limit nebo je zrušen token zrušení před dokončením úkolu.The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes. |
| Wait(TimeSpan) |
Čeká na Task dokončení provádění během zadaného časového intervalu.Waits for the Task to complete execution within a specified time interval. |
| Wait(Int32) |
Čeká na Task dokončení provádění během zadaného počtu milisekund.Waits for the Task to complete execution within a specified number of milliseconds. |
| Wait(CancellationToken) |
Čeká na Task dokončení provádění.Waits for the Task to complete execution. Čekání skončí, pokud je zrušený token zrušení před dokončením úkolu.The wait terminates if a cancellation token is canceled before the task completes. |
| Wait() |
Čeká na Task dokončení provádění.Waits for the Task to complete execution. |
Wait(Int32, CancellationToken)
public:
bool Wait(int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
public bool Wait (int millisecondsTimeout, System.Threading.CancellationToken cancellationToken);
member this.Wait : int * System.Threading.CancellationToken -> bool
Public Function Wait (millisecondsTimeout As Integer, cancellationToken As CancellationToken) As Boolean
Parametry
- millisecondsTimeout
- Int32
Počet milisekund, po které se má čekat, nebo Infinite (-1) na čekání na neomezenou dobu.The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.
- cancellationToken
- CancellationToken
Token zrušení, který se má sledovat při čekání na dokončení úlohy.A cancellation token to observe while waiting for the task to complete.
Návraty
true Pokud Task bylo dokončeno provedení v přiděleném čase; v opačném případě false .true if the Task completed execution within the allotted time; otherwise, false.
Výjimky
cancellationTokenByla zrušena.The cancellationToken was canceled.
millisecondsTimeout je záporné číslo jiné než-1, které představuje nekonečný časový limit.millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.
Úloha byla zrušena.The task was canceled. InnerExceptionsKolekce obsahuje TaskCanceledException objekt.The InnerExceptions collection contains a TaskCanceledException object.
-nebo--or- Během provádění úlohy byla vyvolána výjimka.An exception was thrown during the execution of the task. InnerExceptionsKolekce obsahuje informace o výjimce nebo výjimkách.The InnerExceptions collection contains information about the exception or exceptions.
Příklady
Následující příklad volá Wait(Int32, CancellationToken) metodu pro poskytnutí hodnoty časového limitu a tokenu zrušení, který může ukončit čekání na dokončení úkolu.The following example calls the Wait(Int32, CancellationToken) method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. Je spuštěno nové vlákno a provede CancelToken metodu, která pozastaví a pak zavolá CancellationTokenSource.Cancel metodu pro zrušení tokenů zrušení.A new thread is started and executes the CancelToken method, which pauses and then calls the CancellationTokenSource.Cancel method to cancel the cancellation tokens. Úkol se pak spustí a zpoždění po dobu 5 sekund.A task is then launched and delays for 5 seconds. WaitMetoda je pak volána pro čekání na dokončení úkolu a je poskytnuta jak pro krátkou hodnotu časového limitu, tak i na token zrušení.The Wait method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
CancellationTokenSource ts = new CancellationTokenSource();
Thread thread = new Thread(CancelToken);
thread.Start(ts);
Task t = Task.Run( () => { Task.Delay(5000).Wait();
Console.WriteLine("Task ended delay...");
});
try {
Console.WriteLine("About to wait completion of task {0}", t.Id);
bool result = t.Wait(1510, ts.Token);
Console.WriteLine("Wait completed normally: {0}", result);
Console.WriteLine("The task status: {0:G}", t.Status);
}
catch (OperationCanceledException e) {
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status);
Thread.Sleep(4000);
Console.WriteLine("After sleeping, the task status: {0:G}", t.Status);
ts.Dispose();
}
}
private static void CancelToken(Object obj)
{
Thread.Sleep(1500);
Console.WriteLine("Canceling the cancellation token from thread {0}...",
Thread.CurrentThread.ManagedThreadId);
CancellationTokenSource source = obj as CancellationTokenSource;
if (source != null) source.Cancel();
}
}
// The example displays output like the following if the wait is canceled by
// the cancellation token:
// About to wait completion of task 1
// Canceling the cancellation token from thread 3...
// OperationCanceledException: The wait has been canceled. Task status: Running
// Task ended delay...
// After sleeping, the task status: RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
// About to wait completion of task 1
// Wait completed normally: False
// The task status: Running
// Canceling the cancellation token from thread 3...
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim ts As New CancellationTokenSource()
Dim thread As New Thread(AddressOf CancelToken)
thread.Start(ts)
Dim t As Task = Task.Run( Sub()
Task.Delay(5000).Wait()
Console.WriteLine("Task ended delay...")
End Sub)
Try
Console.WriteLine("About to wait completion of task {0}", t.Id)
Dim result As Boolean = t.Wait(1510, ts.Token)
Console.WriteLine("Wait completed normally: {0}", result)
Console.WriteLine("The task status: {0:G}", t.Status)
Catch e As OperationCanceledException
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status)
Thread.Sleep(4000)
Console.WriteLine("After sleeping, the task status: {0:G}", t.Status)
ts.Dispose()
End Try
End Sub
Private Sub CancelToken(obj As Object)
Thread.Sleep(1500)
Console.WriteLine("Canceling the cancellation token from thread {0}...",
Thread.CurrentThread.ManagedThreadId)
If TypeOf obj Is CancellationTokenSource Then
Dim source As CancellationTokenSource = CType(obj, CancellationTokenSource)
source.Cancel()
End If
End Sub
End Module
' The example displays output like the following if the wait is canceled by
' the cancellation token:
' About to wait completion of task 1
' Canceling the cancellation token from thread 3...
' OperationCanceledException: The wait has been canceled. Task status: Running
' Task ended delay...
' After sleeping, the task status: RanToCompletion
' The example displays output like the following if the wait is canceled by
' the timeout interval expiring:
' About to wait completion of task 1
' Wait completed normally: False
' The task status: Running
' Canceling the cancellation token from thread 3...
Všimněte si, že přesný výstup z příkladu závisí na tom, zda bylo čekání zrušeno z důvodu tokenu zrušení, nebo vzhledem k tomu, že časový limit vypršel.Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed.
Poznámky
Wait(Int32, CancellationToken) je synchronizační metoda, která způsobí, že volající vlákno počká na dokončení aktuální instance úlohy, dokud neproběhne jedna z následujících akcí:Wait(Int32, CancellationToken) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:
Úloha se úspěšně dokončila.The task completes successfully.
Samotný úkol je zrušen nebo vyvolá výjimku.The task itself is canceled or throws an exception. V tomto případě se zpracuje AggregateException výjimka.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsVlastnost obsahuje podrobnosti o výjimce nebo výjimkách.The AggregateException.InnerExceptions property contains details about the exception or exceptions.
cancellationTokenToken zrušení je zrušený.ThecancellationTokencancellation token is canceled. V tomto případě volání Wait(Int32, CancellationToken) metody vyvolá výjimku OperationCanceledException .In this case, the call to the Wait(Int32, CancellationToken) method throws an OperationCanceledException.Interval definovaný po
millisecondsTimeoutuplynutí doby.The interval defined bymillisecondsTimeoutelapses. V tomto případě aktuální vlákno pokračuje v provádění a metoda se vrátífalse.In this case, the current thread resumes execution and the method returnsfalse.
Poznámka
Zrušení cancellationToken tokenu zrušení nemá žádný vliv na spuštěnou úlohu, pokud to ještě neprošlo token zrušení a je připravené k tomu, aby bylo možné zpracovat zrušení.Canceling the cancellationToken cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Předání cancellationToken objektu této metodě jednoduše umožňuje čekat na zrušení na základě nějaké podmínky.Passing the cancellationToken object to this method simply allows the wait to be canceled based on some condition.
Platí pro
Wait(TimeSpan)
public:
bool Wait(TimeSpan timeout);
public bool Wait (TimeSpan timeout);
member this.Wait : TimeSpan -> bool
Public Function Wait (timeout As TimeSpan) As Boolean
Parametry
- timeout
- TimeSpan
TimeSpanPředstavuje počet milisekund, které se mají čekat, nebo hodnota TimeSpan , která představuje 1 milisekundy na čekání neomezenou dobu.A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.
Návraty
true Pokud Task bylo dokončeno provedení v přiděleném čase; v opačném případě false .true if the Task completed execution within the allotted time; otherwise, false.
Výjimky
timeout je záporné číslo jiné než-1 milisekundy, které představuje nekonečný časový limit.timeout is a negative number other than -1 milliseconds, which represents an infinite time-out.
-nebo--or-
timeout je větší než MaxValue .timeout is greater than MaxValue.
Úloha byla zrušena.The task was canceled. InnerExceptionsKolekce obsahuje TaskCanceledException objekt.The InnerExceptions collection contains a TaskCanceledException object.
-nebo--or- Během provádění úlohy byla vyvolána výjimka.An exception was thrown during the execution of the task. InnerExceptionsKolekce obsahuje informace o výjimce nebo výjimkách.The InnerExceptions collection contains information about the exception or exceptions.
Příklady
Následující příklad spustí úlohu, která generuje 5 000 000 náhodných celých čísel mezi 0 a 100 a vypočítá jejich střední hodnotu.The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. V příkladu se používá Wait(TimeSpan) metoda pro čekání na dokončení aplikace do 150 milisekund.The example uses the Wait(TimeSpan) method to wait for the application to complete within 150 milliseconds. Pokud se aplikace dokončí normálně, úloha zobrazí součet a průměr náhodných čísel, která vygenerovala.If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. Pokud uplynul časový limit, v příkladu se zobrazí zpráva před tím, než se ukončí.If the timeout interval has elapsed, the example displays a message before it terminates.
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task t = Task.Run( () => {
Random rnd = new Random();
long sum = 0;
int n = 5000000;
for (int ctr = 1; ctr <= n; ctr++) {
int number = rnd.Next(0, 101);
sum += number;
}
Console.WriteLine("Total: {0:N0}", sum);
Console.WriteLine("Mean: {0:N2}", sum/n);
Console.WriteLine("N: {0:N0}", n);
} );
TimeSpan ts = TimeSpan.FromMilliseconds(150);
if (! t.Wait(ts))
Console.WriteLine("The timeout interval elapsed.");
}
}
// The example displays output similar to the following:
// Total: 50,015,714
// Mean: 50.02
// N: 1,000,000
// Or it displays the following output:
// The timeout interval elapsed.
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim t As Task = Task.Run( Sub()
Dim rnd As New Random()
Dim sum As Long
Dim n As Integer = 5000000
For ctr As Integer = 1 To n
Dim number As Integer = rnd.Next(0, 101)
sum += number
Next
Console.WriteLine("Total: {0:N0}", sum)
Console.WriteLine("Mean: {0:N2}", sum/n)
Console.WriteLine("N: {0:N0}", n)
End Sub)
Dim ts As TimeSpan = TimeSpan.FromMilliseconds(150)
If Not t.Wait(ts) Then
Console.WriteLine("The timeout interval elapsed.")
End If
End Sub
End Module
' The example displays output similar to the following:
' Total: 50,015,714
' Mean: 50.02
' N: 1,000,000
' Or it displays the following output:
' The timeout interval elapsed.
Poznámky
Wait(TimeSpan) je synchronizační metoda, která způsobí, že volající vlákno počká na dokončení aktuální instance úlohy, dokud neproběhne jedna z následujících akcí:Wait(TimeSpan) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:
Úloha se úspěšně dokončila.The task completes successfully.
Samotný úkol je zrušen nebo vyvolá výjimku.The task itself is canceled or throws an exception. V tomto případě se zpracuje AggregateException výjimka.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsVlastnost obsahuje podrobnosti o výjimce nebo výjimkách.The AggregateException.InnerExceptions property contains details about the exception or exceptions.
Interval definovaný po
timeoutuplynutí doby.The interval defined bytimeoutelapses. V tomto případě aktuální vlákno pokračuje v provádění a metoda se vrátífalse.In this case, the current thread resumes execution and the method returnsfalse.
Platí pro
Wait(Int32)
public:
bool Wait(int millisecondsTimeout);
public bool Wait (int millisecondsTimeout);
member this.Wait : int -> bool
Public Function Wait (millisecondsTimeout As Integer) As Boolean
Parametry
- millisecondsTimeout
- Int32
Počet milisekund, po které se má čekat, nebo Infinite (-1) na čekání na neomezenou dobu.The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.
Návraty
true Pokud Task bylo dokončeno provedení v přiděleném čase; v opačném případě false .true if the Task completed execution within the allotted time; otherwise, false.
Výjimky
millisecondsTimeout je záporné číslo jiné než-1, které představuje nekonečný časový limit.millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.
Úloha byla zrušena.The task was canceled. InnerExceptionsKolekce obsahuje TaskCanceledException objekt.The InnerExceptions collection contains a TaskCanceledException object.
-nebo--or- Během provádění úlohy byla vyvolána výjimka.An exception was thrown during the execution of the task. InnerExceptionsKolekce obsahuje informace o výjimce nebo výjimkách.The InnerExceptions collection contains information about the exception or exceptions.
Příklady
Následující příklad spustí úlohu, která generuje 5 000 000 náhodných celých čísel mezi 0 a 100 a vypočítá jejich střední hodnotu.The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. V příkladu se používá Wait(Int32) metoda pro čekání na dokončení aplikace do 150 milisekund.The example uses the Wait(Int32) method to wait for the application to complete within 150 milliseconds. Pokud se aplikace dokončí normálně, úloha zobrazí součet a průměr náhodných čísel, která vygenerovala.If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. Pokud uplynul časový limit, v příkladu se zobrazí zpráva před tím, než se ukončí.If the timeout interval has elapsed, the example displays a message before it terminates.
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task t = Task.Run( () => {
Random rnd = new Random();
long sum = 0;
int n = 5000000;
for (int ctr = 1; ctr <= n; ctr++) {
int number = rnd.Next(0, 101);
sum += number;
}
Console.WriteLine("Total: {0:N0}", sum);
Console.WriteLine("Mean: {0:N2}", sum/n);
Console.WriteLine("N: {0:N0}", n);
} );
if (! t.Wait(150))
Console.WriteLine("The timeout interval elapsed.");
}
}
// The example displays output similar to the following:
// Total: 50,015,714
// Mean: 50.02
// N: 1,000,000
// Or it displays the following output:
// The timeout interval elapsed.
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim t As Task = Task.Run( Sub()
Dim rnd As New Random()
Dim sum As Long
Dim n As Integer = 5000000
For ctr As Integer = 1 To n
Dim number As Integer = rnd.Next(0, 101)
sum += number
Next
Console.WriteLine("Total: {0:N0}", sum)
Console.WriteLine("Mean: {0:N2}", sum/n)
Console.WriteLine("N: {0:N0}", n)
End Sub)
If Not t.Wait(150) Then
Console.WriteLine("The timeout interval elapsed.")
End If
End Sub
End Module
' The example displays output similar to the following:
' Total: 50,015,714
' Mean: 50.02
' N: 1,000,000
' Or it displays the following output:
' The timeout interval elapsed.
Poznámky
Wait(Int32) je synchronizační metoda, která způsobí, že volající vlákno počká na dokončení aktuální instance úlohy, dokud neproběhne jedna z následujících akcí:Wait(Int32) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:
Úloha se úspěšně dokončila.The task completes successfully.
Samotný úkol je zrušen nebo vyvolá výjimku.The task itself is canceled or throws an exception. V tomto případě se zpracuje AggregateException výjimka.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsVlastnost obsahuje podrobnosti o výjimce nebo výjimkách.The AggregateException.InnerExceptions property contains details about the exception or exceptions.
Interval definovaný po
millisecondsTimeoutuplynutí doby.The interval defined bymillisecondsTimeoutelapses. V tomto případě aktuální vlákno pokračuje v provádění a metoda se vrátífalse.In this case, the current thread resumes execution and the method returnsfalse.
Platí pro
Wait(CancellationToken)
public:
void Wait(System::Threading::CancellationToken cancellationToken);
public void Wait (System.Threading.CancellationToken cancellationToken);
member this.Wait : System.Threading.CancellationToken -> unit
Public Sub Wait (cancellationToken As CancellationToken)
Parametry
- cancellationToken
- CancellationToken
Token zrušení, který se má sledovat při čekání na dokončení úlohy.A cancellation token to observe while waiting for the task to complete.
Výjimky
cancellationTokenByla zrušena.The cancellationToken was canceled.
Úloha byla vyřazena.The task has been disposed.
Úloha byla zrušena.The task was canceled. InnerExceptionsKolekce obsahuje TaskCanceledException objekt.The InnerExceptions collection contains a TaskCanceledException object.
-nebo--or- Během provádění úlohy byla vyvolána výjimka.An exception was thrown during the execution of the task. InnerExceptionsKolekce obsahuje informace o výjimce nebo výjimkách.The InnerExceptions collection contains information about the exception or exceptions.
Příklady
Následující příklad ilustruje jednoduché použití tokenu zrušení ke zrušení čekání na dokončení úkolu.The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. Spustí se úkol, zavolá CancellationTokenSource.Cancel metodu pro zrušení všech tokenů zrušení zdroje tokenu a potom zpoždění po dobu pěti sekund.A task is launched, calls the CancellationTokenSource.Cancel method to cancel any of the token source's cancellation tokens, and then delays for five seconds. Všimněte si, že samotný úkol neprošlý tokenem zrušení a nelze jej zrušit.Note that the task itself has not been passed the cancellation token and is not cancelable. Vlákno aplikace volá Task.Wait metodu úlohy, aby čekala na dokončení úlohy, ale čekání je zrušeno, jakmile je zrušený token zrušení a OperationCanceledException je vyvolána výjimka.The application thread calls the task's Task.Wait method to wait for the task to complete, but the wait is canceled once the cancellation token is cancelled and an OperationCanceledException is thrown. Obslužná rutina výjimky ohlásí výjimku a pak přejde do režimu spánku po dobu šesti sekund.The exception handler reports the exception and then sleeps for six seconds. Jak ukazuje výstup z příkladu, tato prodleva umožňuje dokončení úlohy ve RanToCompletion stavu.As the output from the example shows, that delay allows the task to complete in the RanToCompletion state.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
CancellationTokenSource ts = new CancellationTokenSource();
Task t = Task.Run( () => { Console.WriteLine("Calling Cancel...");
ts.Cancel();
Task.Delay(5000).Wait();
Console.WriteLine("Task ended delay...");
});
try {
Console.WriteLine("About to wait for the task to complete...");
t.Wait(ts.Token);
}
catch (OperationCanceledException e) {
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status);
Thread.Sleep(6000);
Console.WriteLine("After sleeping, the task status: {0:G}", t.Status);
}
ts.Dispose();
}
}
// The example displays output like the following:
// About to wait for the task to complete...
// Calling Cancel...
// OperationCanceledException: The wait has been canceled. Task status: Running
// Task ended delay...
// After sleeping, the task status: RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim ts As New CancellationTokenSource()
Dim t = Task.Run( Sub()
Console.WriteLine("Calling Cancel...")
ts.Cancel()
Task.Delay(5000).Wait()
Console.WriteLine("Task ended delay...")
End Sub)
Try
Console.WriteLine("About to wait for the task to complete...")
t.Wait(ts.Token)
Catch e As OperationCanceledException
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status)
Thread.Sleep(6000)
Console.WriteLine("After sleeping, the task status: {0:G}", t.Status)
End Try
ts.Dispose()
End Sub
End Module
' The example displays output like the following:
' About to wait for the task to complete...
' Calling Cancel...
' OperationCanceledException: The wait has been canceled. Task status: Running
' Task ended delay...
' After sleeping, the task status: RanToCompletion
Poznámky
Wait(CancellationToken)Metoda vytvoří čekání s možností zrušení; to znamená, že aktuální vlákno počká, až nastane jedna z následujících příčin:The Wait(CancellationToken) method creates a cancelable wait; that is, it causes the current thread to wait until one of the following occurs:
Úloha se dokončí.The task completes.
Token zrušení je zrušený.The cancellation token is canceled. V tomto případě volání Wait(CancellationToken) metody vyvolá výjimku OperationCanceledException .In this case, the call to the Wait(CancellationToken) method throws an OperationCanceledException.
Poznámka
Zrušení cancellationToken tokenu zrušení nemá žádný vliv na spuštěnou úlohu, pokud to ještě neprošlo token zrušení a je připravené k tomu, aby bylo možné zpracovat zrušení.Canceling the cancellationToken cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Předání cancellationToken objektu této metodě jednoduše umožňuje počkat na zrušení.Passing the cancellationToken object to this method simply allows the wait to be canceled.
Platí pro
Wait()
public:
void Wait();
public void Wait ();
member this.Wait : unit -> unit
Public Sub Wait ()
Výjimky
Úloha byla zrušena.The task was canceled. InnerExceptionsKolekce obsahuje TaskCanceledException objekt.The InnerExceptions collection contains a TaskCanceledException object.
-nebo--or- Během provádění úlohy byla vyvolána výjimka.An exception was thrown during the execution of the task. InnerExceptionsKolekce obsahuje informace o výjimce nebo výjimkách.The InnerExceptions collection contains information about the exception or exceptions.
Příklady
Následující příklad spustí úlohu, která generuje 1 000 000 náhodných celých čísel mezi 0 a 100 a vypočítá jejich střední hodnotu.The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. V příkladu se používá Wait Metoda k zajištění toho, aby se úloha dokončila před ukončením aplikace.The example uses the Wait method to ensure that the task completes before the application terminates. V opačném případě, vzhledem k tomu, že se jedná o konzolovou aplikaci, může být příklad ukončen před výpočtem úlohy a zobrazením středníku.Otherwise, because this is a console application, the example would terminate before the task can compute and display the mean.
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task t = Task.Run( () => {
Random rnd = new Random();
long sum = 0;
int n = 1000000;
for (int ctr = 1; ctr <= n; ctr++) {
int number = rnd.Next(0, 101);
sum += number;
}
Console.WriteLine("Total: {0:N0}", sum);
Console.WriteLine("Mean: {0:N2}", sum/n);
Console.WriteLine("N: {0:N0}", n);
} );
t.Wait();
}
}
// The example displays output similar to the following:
// Total: 50,015,714
// Mean: 50.02
// N: 1,000,000
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim t As Task = Task.Run( Sub()
Dim rnd As New Random()
Dim sum As Long
Dim n As Integer = 1000000
For ctr As Integer = 1 To n
Dim number As Integer = rnd.Next(0, 101)
sum += number
Next
Console.WriteLine("Total: {0:N0}", sum)
Console.WriteLine("Mean: {0:N2}", sum/n)
Console.WriteLine("N: {0:N0}", n)
End Sub)
t.Wait()
End Sub
End Module
' The example displays output similar to the following:
' Total: 50,015,714
' Mean: 50.02
' N: 1,000,000
Poznámky
Wait je synchronizační metoda, která způsobí, že volající vlákno počká na dokončení aktuální úlohy.Wait is a synchronization method that causes the calling thread to wait until the current task has completed. Pokud aktuální úloha nezačala provádět, pokusí se metoda čekání odebrat úlohu z plánovače a spustit ji v aktuálním vlákně jako vloženou.If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. Pokud to není možné, nebo pokud aktuální úloha již začala spustit, blokuje volající vlákno, dokud se úloha nedokončí.If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes. Další informace najdete v tématu Task. Wait a " informing" v rámci paralelního programování pomocí blogu .NET.For more information, see Task.Wait and "Inlining" in the Parallel Programming with .NET blog.