Task.Wait 메서드

정의

Task의 실행이 완료되기를 기다립니다.

오버로드

Wait()

Task의 실행이 완료되기를 기다립니다.

Wait(Int32)

Task가 지정된 시간(밀리초) 내에 실행을 완료할 때까지 기다립니다.

Wait(CancellationToken)

Task의 실행이 완료되기를 기다립니다. 작업이 완료되기 전에 취소 토큰이 취소되면 대기가 종료됩니다.

Wait(TimeSpan)

Task가 지정된 시간 간격 내에 실행을 완료할 때까지 기다립니다.

Wait(Int32, CancellationToken)

Task의 실행이 완료되기를 기다립니다. 작업이 완료되기 전에 취소 토큰이 취소되었거나 시간 제한 간격이 경과되었으면 대기가 종료됩니다.

Wait(TimeSpan, CancellationToken)

Task의 실행이 완료되기를 기다립니다.

Wait()

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 개체가 있습니다.

또는

작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 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 및 "Inlining" 을 참조하세요.

추가 정보

적용 대상

Wait(Int32)

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

매개 변수

millisecondsTimeout
Int32

대기할 시간(밀리초)이거나, 무기한 대기할 경우 Infinite(-1)입니다.

반환

true의 실행이 할당된 시간 안에 완료되었으면 Task이고, 그렇지 않으면 false입니다.

예외

Task가 삭제된 경우

millisecondsTimeout이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우

작업이 취소되었습니다. InnerExceptions 컬렉션에 TaskCanceledException 개체가 있습니다.

또는

작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 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)는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 instance 완료될 때까지 대기하도록 하는 동기화 메서드입니다.

  • 작업이 성공적으로 완료됩니다.

  • 작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함됩니다.

  • 경과로 millisecondsTimeout 정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 를 반환합니다 false.

적용 대상

Wait(CancellationToken)

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 개체가 있습니다.

또는

작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 InnerExceptions 컬렉션입니다.

예제

다음 예제에서는 취소 토큰을 간단하게 사용하여 작업 완료 대기를 취소하는 방법을 보여 줍니다. 작업이 시작되고 메서드를 CancellationTokenSource.Cancel 호출하여 토큰 원본의 취소 토큰을 취소한 다음 5초 동안 지연됩니다. 작업 자체가 취소 토큰을 전달하지 않았으며 취소할 수 없습니다. 작업을 호출 하는 애플리케이션 스레드에 Task.Wait 메서드는 작업이 완료 될 때까지 기다리는를 있지만 대기 취소 토큰이 취소 되 면 및 취소 OperationCanceledException throw 됩니다. 예외 처리기는 예외를 보고한 다음 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) 취소 가능한 대기를 만듭니다. 즉, 다음 중 하나가 발생할 때까지 현재 스레드가 대기합니다.

참고

cancellationToken 취소 토큰도 전달되고 취소를 처리할 준비가 되어 있지 않으면 취소 토큰을 취소해도 실행 중인 작업에 영향을 주지 않습니다. 개체를 cancellationToken 이 메서드에 전달하면 대기를 취소할 수 있습니다.

적용 대상

Wait(TimeSpan)

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

매개 변수

timeout
TimeSpan

대기할 시간(밀리초)을 나타내는 TimeSpan이거나, 무한 대기하도록 -1밀리초를 나타내는 TimeSpan입니다.

반환

true의 실행이 할당된 시간 안에 완료되었으면 Task이고, 그렇지 않으면 false입니다.

예외

Task가 삭제된 경우

timeout 은 시간 제한이 없음을 나타내는 -1밀리초 이외의 음수입니다.

또는

timeoutInt32.MaxValue보다 큽 수 있습니다.

작업이 취소되었습니다. InnerExceptions 컬렉션에 TaskCanceledException 개체가 있습니다.

또는

작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 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)는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 instance 완료될 때까지 대기하도록 하는 동기화 메서드입니다.

  • 작업이 성공적으로 완료됩니다.

  • 작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함됩니다.

  • 경과로 timeout 정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 를 반환합니다 false.

적용 대상

Wait(Int32, CancellationToken)

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

매개 변수

millisecondsTimeout
Int32

대기할 시간(밀리초)이거나, 무기한 대기할 경우 Infinite(-1)입니다.

cancellationToken
CancellationToken

작업이 완료되기를 기다리는 동안 관찰할 취소 토큰입니다.

반환

true의 실행이 할당된 시간 안에 완료되었으면 Task이고, 그렇지 않으면 false입니다.

예외

cancellationToken을 취소했습니다.

Task가 삭제된 경우

millisecondsTimeout이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우

작업이 취소되었습니다. InnerExceptions 컬렉션에 TaskCanceledException 개체가 있습니다.

또는

작업을 실행하는 동안 예외가 발생한 경우 예외나 예외에 대한 정보를 포함하는 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)는 호출 스레드가 다음 중 하나가 발생할 때까지 현재 작업 instance 완료될 때까지 대기하도록 하는 동기화 메서드입니다.

  • 작업이 성공적으로 완료됩니다.

  • 작업 자체가 취소되거나 예외가 throw됩니다. 이 경우 예외를 처리합니다 AggregateException . 속성에는 AggregateException.InnerExceptions 예외 또는 예외에 대한 세부 정보가 포함되어 있습니다.

  • cancellationToken 취소 토큰이 취소되었습니다. 이 경우 메서드에 대한 호출은 Wait(Int32, CancellationToken)OperationCanceledExceptionthrow합니다.

  • 경과로 millisecondsTimeout 정의된 간격입니다. 이 경우 현재 스레드는 실행을 다시 시작하고 메서드는 를 반환합니다 false.

참고

취소 토큰도 cancellationToken 전달되고 취소를 처리할 준비가 되어 있지 않으면 취소 토큰을 취소하면 실행 중인 작업에 영향을 주지 않습니다. 개체를 cancellationToken 이 메서드에 전달하면 일부 조건에 따라 대기를 취소할 수 있습니다.

적용 대상

Wait(TimeSpan, CancellationToken)

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 작업이 완료 될 때까지 기다리는 동안 관찰할 입니다.

반환

true의 실행이 할당된 시간 안에 완료되었으면 Task이고, 그렇지 않으면 false입니다.

예외

Task 취소되었습니다.

또는

를 실행하는 동안 예외가 throw되었습니다 Task.

timeout 는 무한 제한 시간을 나타내는 -1밀리초 이외의 음수입니다.

또는

제한 시간이 보다 큽 MaxValue다.

cancellationToken을 취소했습니다.

적용 대상