Task.Wait 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
실행이 Task 완료되기를 기다립니다.
오버로드
| Name | Description |
|---|---|
| Wait(TimeSpan, CancellationToken) |
실행이 Task 완료되기를 기다립니다. |
| Wait(Int32, CancellationToken) |
실행이 Task 완료되기를 기다립니다. 태스크가 완료되기 전에 시간 제한 간격이 경과하거나 취소 토큰이 취소되면 대기가 종료됩니다. |
| Wait(TimeSpan) |
Task 지정된 시간 간격 내에 실행이 완료될 때까지 기다립니다. |
| Wait(CancellationToken) |
실행이 Task 완료되기를 기다립니다. 작업이 완료되기 전에 취소 토큰이 취소되면 대기가 종료됩니다. |
| Wait() |
실행이 Task 완료되기를 기다립니다. |
| Wait(Int32) |
Task 지정된 시간(밀리초) 내에 실행이 완료될 때까지 기다립니다. |
Wait(TimeSpan, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
실행이 Task 완료되기를 기다립니다.
public:
bool Wait(TimeSpan timeout, System::Threading::CancellationToken cancellationToken);
public bool Wait(TimeSpan timeout, System.Threading.CancellationToken cancellationToken);
member this.Wait : TimeSpan * System.Threading.CancellationToken -> bool
Public Function Wait (timeout As TimeSpan, cancellationToken As CancellationToken) As Boolean
매개 변수
- timeout
- TimeSpan
대기하거나 InfiniteTimeSpan 무기한 대기할 시간
- cancellationToken
- CancellationToken
CancellationToken 작업이 완료 될 때까지 기다리는 동안 관찰할 A입니다.
반환
true
Task 할당된 시간 내에 완료된 실행이면 이고, false그렇지 않으면 .
예외
cancellationToken을 취소했습니다.
적용 대상
Wait(Int32, CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
실행이 Task 완료되기를 기다립니다. 태스크가 완료되기 전에 시간 제한 간격이 경과하거나 취소 토큰이 취소되면 대기가 종료됩니다.
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
매개 변수
- cancellationToken
- CancellationToken
작업이 완료 될 때까지 기다리는 동안 관찰할 취소 토큰입니다.
반환
true
Task 할당된 시간 내에 완료된 실행이면 이고, false그렇지 않으면 .
예외
cancellationToken을 취소했습니다.
Task 삭제되었습니다.
millisecondsTimeout 는 무한 제한 시간을 나타내는 -1 이외의 음수입니다.
작업이 취소되었습니다. 컬렉션에 InnerExceptions 개체가 포함되어 있습니다 TaskCanceledException .
-또는-
작업을 실행하는 동안 예외가 throw되었습니다. 컬렉션에는 InnerExceptions 예외 또는 예외에 대한 정보가 포함됩니다.
예제
다음 예제에서는 시간 제한 값 및 작업의 완료 대기를 종료할 수 있는 취소 토큰을 제공 하는 메서드를 호출 Wait(Int32, CancellationToken) 합니다. 새 스레드가 시작되고 메서드를 CancelToken 실행합니다. 이 메서드는 일시 중지된 다음 메서드를 호출 CancellationTokenSource.Cancel 하여 취소 토큰을 취소합니다. 그런 다음 작업이 시작되고 5초 동안 지연됩니다.
Wait 그런 다음 이 메서드는 작업의 완료를 기다리도록 호출되며 간단한 시간 제한 값과 취소 토큰이 모두 제공됩니다.
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...
open System
open System.Threading
open System.Threading.Tasks
let cancelToken (obj: obj) =
Thread.Sleep 1500
printfn $"Canceling the cancellation token from thread {Thread.CurrentThread.ManagedThreadId}..."
match obj with
| :? CancellationTokenSource as source -> source.Cancel()
| _ -> ()
let ts = new CancellationTokenSource()
let thread = Thread(ParameterizedThreadStart cancelToken)
thread.Start ts
let t =
Task.Run(fun () ->
Task.Delay(5000).Wait()
printfn "Task ended delay...")
try
printfn $"About to wait completion of task {t.Id}"
let result = t.Wait(1510, ts.Token)
printfn $"Wait completed normally: {result}"
printfn $"The task status: {t.Status:G}"
with :? OperationCanceledException as e ->
printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
Thread.Sleep 4000
printfn $"After sleeping, the task status: {t.Status:G}"
ts.Dispose()
// 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...
예제의 정확한 출력은 취소 토큰으로 인해 대기가 취소되었는지 또는 시간 제한 간격이 경과했기 때문에 취소되었는지에 따라 달라집니다.
설명
Wait(Int32, CancellationToken) 는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 인스턴스가 완료될 때까지 대기하게 하는 동기화 메서드입니다.
작업이 성공적으로 완료됩니다.
작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 이 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함되어 있습니다.
cancellationToken취소 토큰이 취소됩니다. 이 경우 메서드에 대한 호출은 Wait(Int32, CancellationToken) .를 OperationCanceledExceptionthrow합니다.경과로
millisecondsTimeout정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 반환합니다false.
메모
cancellationToken 취소 토큰도 전달되고 취소를 처리할 준비가 되어 있지 않으면 취소 토큰을 취소해도 실행 중인 작업에 영향을 주지 않습니다. 이 메서드에 cancellationToken 개체를 전달하면 일부 조건에 따라 대기를 취소할 수 있습니다.
적용 대상
Wait(TimeSpan)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
Task 지정된 시간 간격 내에 실행이 완료될 때까지 기다립니다.
public:
bool Wait(TimeSpan timeout);
public bool Wait(TimeSpan timeout);
member this.Wait : TimeSpan -> bool
Public Function Wait (timeout As TimeSpan) As Boolean
매개 변수
반환
true
Task 할당된 시간 내에 완료된 실행이면 이고, false그렇지 않으면 .
예외
Task 삭제되었습니다.
작업이 취소되었습니다. 컬렉션에 InnerExceptions 개체가 포함되어 있습니다 TaskCanceledException .
-또는-
작업을 실행하는 동안 예외가 throw되었습니다. 컬렉션에는 InnerExceptions 예외 또는 예외에 대한 정보가 포함됩니다.
예제
다음 예제에서는 0에서 100 사이의 5백만 개의 임의 정수를 생성하고 해당 평균을 계산하는 작업을 시작합니다. 이 예제에서는 이 메서드를 사용하여 Wait(TimeSpan) 애플리케이션이 150밀리초 이내에 완료될 때까지 기다립니다. 애플리케이션이 정상적으로 완료되면 태스크는 생성된 난수의 합계와 평균을 표시합니다. 시간 제한 간격이 경과된 경우 종료되기 전에 메시지를 표시하는 예제입니다.
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.
open System
open System.Threading.Tasks
let t =
Task.Run(fun () ->
let rnd = Random()
let mutable sum = 0L
let n = 5000000
for _ = 1 to n do
let number = rnd.Next(0, 101)
sum <- sum + int64 number
printfn $"Total: {sum:N0}"
printfn $"Mean: {float sum / float n:N2}"
printfn $"N: {n:N0}")
let ts = TimeSpan.FromMilliseconds 150
if t.Wait ts |> not then
printfn "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.
설명
Wait(TimeSpan) 는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 인스턴스가 완료될 때까지 대기하게 하는 동기화 메서드입니다.
작업이 성공적으로 완료됩니다.
작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 이 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함되어 있습니다.
경과로
timeout정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 반환합니다false.
적용 대상
Wait(CancellationToken)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
실행이 Task 완료되기를 기다립니다. 작업이 완료되기 전에 취소 토큰이 취소되면 대기가 종료됩니다.
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)
매개 변수
- cancellationToken
- CancellationToken
작업이 완료 될 때까지 기다리는 동안 관찰할 취소 토큰입니다.
예외
cancellationToken을 취소했습니다.
작업이 삭제되었습니다.
작업이 취소되었습니다. 컬렉션에 InnerExceptions 개체가 포함되어 있습니다 TaskCanceledException .
-또는-
작업을 실행하는 동안 예외가 throw되었습니다. 컬렉션에는 InnerExceptions 예외 또는 예외에 대한 정보가 포함됩니다.
예제
다음 예제에서는 작업의 완료 대기를 취소하기 위해 취소 토큰을 간단히 사용하는 방법을 보여 줍니다. 작업이 시작되고, 메서드를 호출 CancellationTokenSource.Cancel 하여 토큰 원본의 취소 토큰을 취소한 다음, 5초 동안 지연됩니다. 작업 자체가 취소 토큰을 전달하지 않았으며 취소할 수 없습니다. 애플리케이션 스레드는 태스크의 Task.Wait 메서드를 호출하여 태스크가 완료될 때까지 대기하지만 취소 토큰이 취소되고 throw되면 대기가 OperationCanceledException 취소됩니다. 예외 처리기는 예외를 보고한 다음 6초 동안 대기합니다. 예제의 출력에서와 같이 해당 지연을 통해 태스크가 상태에서 완료 RanToCompletion 됩니다.
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
open System
open System.Threading
open System.Threading.Tasks
let ts = new CancellationTokenSource()
let t =
Task.Run(fun () ->
printfn "Calling Cancel..."
ts.Cancel()
Task.Delay(5000).Wait()
printfn $"Task ended delay...")
try
printfn "About to wait for the task to complete..."
t.Wait ts.Token
with :? OperationCanceledException as e ->
printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
Thread.Sleep 6000
printfn $"After sleeping, the task status: {t.Status:G}"
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
설명
이 메서드는 Wait(CancellationToken) 취소 가능한 대기를 만듭니다. 즉, 다음 중 하나가 발생할 때까지 현재 스레드가 대기합니다.
작업이 완료됩니다.
취소 토큰이 취소됩니다. 이 경우 메서드에 대한 호출은 Wait(CancellationToken) .를 OperationCanceledExceptionthrow합니다.
메모
cancellationToken 취소 토큰도 전달되고 취소를 처리할 준비가 되어 있지 않으면 취소 토큰을 취소해도 실행 중인 작업에 영향을 주지 않습니다. 이 메서드에 cancellationToken 개체를 전달하면 대기를 취소할 수 있습니다.
적용 대상
Wait()
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
실행이 Task 완료되기를 기다립니다.
public:
void Wait();
public void Wait();
member this.Wait : unit -> unit
Public Sub Wait ()
예외
Task 삭제되었습니다.
작업이 취소되었습니다. 컬렉션에 InnerExceptions 개체가 포함되어 있습니다 TaskCanceledException .
-또는-
작업을 실행하는 동안 예외가 throw되었습니다. 컬렉션에는 InnerExceptions 예외 또는 예외에 대한 정보가 포함됩니다.
예제
다음 예제에서는 0에서 100 사이의 100만 개의 임의 정수를 생성하고 해당 평균을 계산하는 작업을 시작합니다. 이 예제에서는 메서드를 Wait 사용하여 애플리케이션이 종료되기 전에 태스크가 완료되도록 합니다. 그렇지 않으면 콘솔 애플리케이션이므로 태스크가 평균을 계산하고 표시하기 전에 예제가 종료됩니다.
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
open System
open System.Threading.Tasks
let t =
Task.Run(fun () ->
let rnd = Random()
let mutable sum = 0L
let n = 1000000
for _ = 1 to n do
let number = rnd.Next(0, 101)
sum <- sum + int64 number
printfn $"Total: {sum:N0}"
printfn $"Mean: {float sum / float n:N2}"
printfn $"N: {n:N0}")
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
설명
Wait 는 현재 작업이 완료될 때까지 호출 스레드가 대기하도록 하는 동기화 메서드입니다. 현재 작업이 실행을 시작하지 않은 경우 Wait 메서드는 스케줄러에서 작업을 제거하고 현재 스레드에서 인라인으로 실행하려고 시도합니다. 이 작업을 수행할 수 없거나 현재 작업이 이미 실행을 시작한 경우 태스크가 완료될 때까지 호출 스레드를 차단합니다. 자세한 내용은 .NET을 사용한 병렬 프로그래밍 블로그 에서 Task.Wait 및 "인라인 처리" 를 참조하세요.
추가 정보
적용 대상
Wait(Int32)
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
- Source:
- Task.cs
Task 지정된 시간(밀리초) 내에 실행이 완료될 때까지 기다립니다.
public:
bool Wait(int millisecondsTimeout);
public bool Wait(int millisecondsTimeout);
member this.Wait : int -> bool
Public Function Wait (millisecondsTimeout As Integer) As Boolean
매개 변수
반환
true
Task 할당된 시간 내에 완료된 실행이면 이고, false그렇지 않으면 .
예외
Task 삭제되었습니다.
millisecondsTimeout 는 무한 제한 시간을 나타내는 -1 이외의 음수입니다.
작업이 취소되었습니다. 컬렉션에 InnerExceptions 개체가 포함되어 있습니다 TaskCanceledException .
-또는-
작업을 실행하는 동안 예외가 throw되었습니다. 컬렉션에는 InnerExceptions 예외 또는 예외에 대한 정보가 포함됩니다.
예제
다음 예제에서는 0에서 100 사이의 5백만 개의 임의 정수를 생성하고 해당 평균을 계산하는 작업을 시작합니다. 이 예제에서는 이 메서드를 사용하여 Wait(Int32) 애플리케이션이 150밀리초 이내에 완료될 때까지 기다립니다. 애플리케이션이 정상적으로 완료되면 태스크는 생성된 난수의 합계와 평균을 표시합니다. 시간 제한 간격이 경과된 경우 종료되기 전에 메시지를 표시하는 예제입니다.
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.
open System
open System.Threading.Tasks
let t =
Task.Run(fun () ->
let rnd = Random()
let mutable sum = 0L
let n = 5000000
for _ = 1 to n do
let number = rnd.Next(0, 101)
sum <- sum + int64 number
printfn $"Total: {sum:N0}"
printfn $"Mean: {float sum / float n:N2}"
printfn $"N: {n:N0}")
if t.Wait 150 |> not then
printfn "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.
설명
Wait(Int32) 는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 인스턴스가 완료될 때까지 대기하게 하는 동기화 메서드입니다.
작업이 성공적으로 완료됩니다.
작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 이 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함되어 있습니다.
경과로
millisecondsTimeout정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 반환합니다false.