Task.Wait Yöntem

Tanım

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution.

Aşırı Yüklemeler

Wait(Int32, CancellationToken)

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution. Bir zaman aşımı aralığı geçtiğinde veya bir iptal belirteci, görev tamamlanmadan önce iptal edilirse, bekleme sona erer.The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

Wait(TimeSpan)

TaskBelirtilen bir zaman aralığı içinde yürütmenin tamamlanmasını bekler.Waits for the Task to complete execution within a specified time interval.

Wait(Int32)

TaskBelirtilen sayıda milisaniye içinde yürütmenin tamamlanmasını bekler.Waits for the Task to complete execution within a specified number of milliseconds.

Wait(CancellationToken)

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution. Bekleme, görev tamamlanmadan iptal belirteci iptal edilirse sonlanır.The wait terminates if a cancellation token is canceled before the task completes.

Wait()

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution.

Wait(Int32, CancellationToken)

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution. Bir zaman aşımı aralığı geçtiğinde veya bir iptal belirteci, görev tamamlanmadan önce iptal edilirse, bekleme sona erer.The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

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

Parametreler

millisecondsTimeout
Int32

Süresiz olarak beklenecek, beklenecek milisaniye sayısı veya Infinite (-1).The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.

cancellationToken
CancellationToken

Görevin tamamlanması beklenirken gözlemlemeye yönelik bir iptal belirteci.A cancellation token to observe while waiting for the task to complete.

Döndürülenler

Boolean

trueTaskbelirlenen süre içinde tamamlanmış yürütme, aksi durumda, false .true if the Task completed execution within the allotted time; otherwise, false.

Özel durumlar

cancellationTokenİptal edildi.The cancellationToken was canceled.

TaskAtıldı.The Task has been disposed.

millisecondsTimeout sonsuz bir zaman aşımını temsil eden-1 dışında negatif bir sayıdır.millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

Görev iptal edildi.The task was canceled. InnerExceptionsKoleksiyon bir nesne içeriyor TaskCanceledException .The InnerExceptions collection contains a TaskCanceledException object.

-veya--or- Görevin yürütülmesi sırasında bir özel durum oluştu.An exception was thrown during the execution of the task. InnerExceptionsKoleksiyon, özel durum veya özel durumlar hakkında bilgiler içerir.The InnerExceptions collection contains information about the exception or exceptions.

Örnekler

Aşağıdaki örnek, Wait(Int32, CancellationToken) hem bir zaman aşımı değeri hem de bir görevin tamamlanmasını beklemeyi sona erdirmek için bir iptal belirteci sağlamak üzere yöntemini çağırır.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. Yeni bir iş parçacığı başlatılır ve yöntemini yürütür ve CancelToken sonra CancellationTokenSource.Cancel iptal belirteçlerini iptal etmek için yöntemini çağırır.A new thread is started and executes the CancelToken method, which pauses and then calls the CancellationTokenSource.Cancel method to cancel the cancellation tokens. Daha sonra bir görev başlatılır ve 5 saniye geciktir.A task is then launched and delays for 5 seconds. WaitDaha sonra yöntem, görevin tamamlanmasını beklemek için çağrılır ve hem kısa bir zaman aşımı değeri hem de bir iptal belirteci sağlanır.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...

Örnekteki kesin çıktının, iptal belirteci nedeniyle veya zaman aşımı aralığı sona erdiğinde beklendiğine göre değişir.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.

Açıklamalar

Wait(Int32, CancellationToken) , çağıran iş parçacığının, aşağıdakilerden biri gerçekleşene kadar geçerli görev örneğinin tamamlanmasını beklemesini neden olan bir eşitleme yöntemidir: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:

  • Görev başarıyla tamamlandı.The task completes successfully.

  • Görevin kendisi iptal edilir veya bir özel durum oluşturur.The task itself is canceled or throws an exception. Bu durumda, bir AggregateException özel durum işleolursunuz.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsÖzelliği, özel durum veya özel durumlar hakkındaki ayrıntıları içerir.The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • cancellationTokenİptal belirteci iptal edildi.The cancellationToken cancellation token is canceled. Bu durumda, yöntemine yapılan çağrı Wait(Int32, CancellationToken) bir oluşturur OperationCanceledException .In this case, the call to the Wait(Int32, CancellationToken) method throws an OperationCanceledException.

  • Tarafından tanımlanan Aralık millisecondsTimeout sona erdiğinde.The interval defined by millisecondsTimeout elapses. Bu durumda, geçerli iş parçacığı yürütmeyi sürdürür ve yöntemi döner false .In this case, the current thread resumes execution and the method returns false.

Not

İptal belirtecinin iptal edilmesi, cancellationToken aynı zamanda iptal belirtecini geçirmediği ve iptali işlemeye hazırlanmadığı takdirde, çalışan görev üzerinde hiçbir etkiye sahip değildir.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. cancellationTokenNesnesini bu yönteme geçirmek yalnızca bir koşula bağlı olarak bekleme durumunun iptal edilmesine izin verir.Passing the cancellationToken object to this method simply allows the wait to be canceled based on some condition.

Şunlara uygulanır

Wait(TimeSpan)

TaskBelirtilen bir zaman aralığı içinde yürütmenin tamamlanmasını bekler.Waits for the Task to complete execution within a specified time interval.

public:
 bool Wait(TimeSpan timeout);
public bool Wait (TimeSpan timeout);
member this.Wait : TimeSpan -> bool
Public Function Wait (timeout As TimeSpan) As Boolean

Parametreler

timeout
TimeSpan

TimeSpanBeklenmesi gereken milisaniye sayısını veya TimeSpan süresiz olarak beklenecek-1 milisaniyeyi temsil eden bir.A TimeSpan that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.

Döndürülenler

Boolean

trueTaskbelirlenen süre içinde tamamlanmış yürütme, aksi durumda, false .true if the Task completed execution within the allotted time; otherwise, false.

Özel durumlar

TaskAtıldı.The Task has been disposed.

timeout sonsuz bir zaman aşımını temsil eden-1 milisaniyelik dışında negatif bir sayıdır.timeout is a negative number other than -1 milliseconds, which represents an infinite time-out. -veya--or- timeout Şundan büyüktür MaxValue .timeout is greater than MaxValue.

Görev iptal edildi.The task was canceled. InnerExceptionsKoleksiyon bir nesne içeriyor TaskCanceledException .The InnerExceptions collection contains a TaskCanceledException object.

-veya--or- Görevin yürütülmesi sırasında bir özel durum oluştu.An exception was thrown during the execution of the task. InnerExceptionsKoleksiyon, özel durum veya özel durumlar hakkında bilgiler içerir.The InnerExceptions collection contains information about the exception or exceptions.

Örnekler

Aşağıdaki örnek 0 ile 100 arasında 5.000.000 rastgele tamsayılar üreten ve bunların Ortalama değerlerini hesaplayan bir görevi başlatır.The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. Örnek, Wait(TimeSpan) uygulamanın 150 milisaniye içinde tamamlanmasını beklemek için yöntemini kullanır.The example uses the Wait(TimeSpan) method to wait for the application to complete within 150 milliseconds. Uygulama normal şekilde tamamlanırsa, görev, oluşturduğu rastgele sayıların toplamını ve ortalaması görüntüler.If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. Zaman aşımı aralığı geçtiğinde, örnek sonlandırılmadan önce bir ileti görüntüler.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.

Açıklamalar

Wait(TimeSpan) , çağıran iş parçacığının, aşağıdakilerden biri gerçekleşene kadar geçerli görev örneğinin tamamlanmasını beklemesini neden olan bir eşitleme yöntemidir: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:

  • Görev başarıyla tamamlandı.The task completes successfully.

  • Görevin kendisi iptal edilir veya bir özel durum oluşturur.The task itself is canceled or throws an exception. Bu durumda, bir AggregateException özel durum işleolursunuz.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsÖzelliği, özel durum veya özel durumlar hakkındaki ayrıntıları içerir.The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • Tarafından tanımlanan Aralık timeout sona erdiğinde.The interval defined by timeout elapses. Bu durumda, geçerli iş parçacığı yürütmeyi sürdürür ve yöntemi döner false .In this case, the current thread resumes execution and the method returns false.

Şunlara uygulanır

Wait(Int32)

TaskBelirtilen sayıda milisaniye içinde yürütmenin tamamlanmasını bekler.Waits for the Task to complete execution within a specified number of milliseconds.

public:
 bool Wait(int millisecondsTimeout);
public bool Wait (int millisecondsTimeout);
member this.Wait : int -> bool
Public Function Wait (millisecondsTimeout As Integer) As Boolean

Parametreler

millisecondsTimeout
Int32

Süresiz olarak beklenecek, beklenecek milisaniye sayısı veya Infinite (-1).The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.

Döndürülenler

Boolean

trueTaskbelirlenen süre içinde tamamlanmış yürütme, aksi durumda, false .true if the Task completed execution within the allotted time; otherwise, false.

Özel durumlar

TaskAtıldı.The Task has been disposed.

millisecondsTimeout sonsuz bir zaman aşımını temsil eden-1 dışında negatif bir sayıdır.millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

Görev iptal edildi.The task was canceled. InnerExceptionsKoleksiyon bir nesne içeriyor TaskCanceledException .The InnerExceptions collection contains a TaskCanceledException object.

-veya--or- Görevin yürütülmesi sırasında bir özel durum oluştu.An exception was thrown during the execution of the task. InnerExceptionsKoleksiyon, özel durum veya özel durumlar hakkında bilgiler içerir.The InnerExceptions collection contains information about the exception or exceptions.

Örnekler

Aşağıdaki örnek 0 ile 100 arasında 5.000.000 rastgele tamsayılar üreten ve bunların Ortalama değerlerini hesaplayan bir görevi başlatır.The following example starts a task that generates five million random integers between 0 and 100 and computes their mean. Örnek, Wait(Int32) uygulamanın 150 milisaniye içinde tamamlanmasını beklemek için yöntemini kullanır.The example uses the Wait(Int32) method to wait for the application to complete within 150 milliseconds. Uygulama normal şekilde tamamlanırsa, görev, oluşturduğu rastgele sayıların toplamını ve ortalaması görüntüler.If the application completes normally, the task displays the sum and mean of the random numbers that it has generated. Zaman aşımı aralığı geçtiğinde, örnek sonlandırılmadan önce bir ileti görüntüler.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.

Açıklamalar

Wait(Int32) , çağıran iş parçacığının, aşağıdakilerden biri gerçekleşene kadar geçerli görev örneğinin tamamlanmasını beklemesini neden olan bir eşitleme yöntemidir: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:

  • Görev başarıyla tamamlandı.The task completes successfully.

  • Görevin kendisi iptal edilir veya bir özel durum oluşturur.The task itself is canceled or throws an exception. Bu durumda, bir AggregateException özel durum işleolursunuz.In this case, you handle an AggregateException exception. AggregateException.InnerExceptionsÖzelliği, özel durum veya özel durumlar hakkındaki ayrıntıları içerir.The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • Tarafından tanımlanan Aralık millisecondsTimeout sona erdiğinde.The interval defined by millisecondsTimeout elapses. Bu durumda, geçerli iş parçacığı yürütmeyi sürdürür ve yöntemi döner false .In this case, the current thread resumes execution and the method returns false.

Şunlara uygulanır

Wait(CancellationToken)

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution. Bekleme, görev tamamlanmadan iptal belirteci iptal edilirse sonlanır.The wait terminates if a cancellation token is canceled before the task completes.

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)

Parametreler

cancellationToken
CancellationToken

Görevin tamamlanması beklenirken gözlemlemeye yönelik bir iptal belirteci.A cancellation token to observe while waiting for the task to complete.

Özel durumlar

cancellationTokenİptal edildi.The cancellationToken was canceled.

Görev atıldı.The task has been disposed.

Görev iptal edildi.The task was canceled. InnerExceptionsKoleksiyon bir nesne içeriyor TaskCanceledException .The InnerExceptions collection contains a TaskCanceledException object.

-veya--or- Görevin yürütülmesi sırasında bir özel durum oluştu.An exception was thrown during the execution of the task. InnerExceptionsKoleksiyon, özel durum veya özel durumlar hakkında bilgiler içerir.The InnerExceptions collection contains information about the exception or exceptions.

Örnekler

Aşağıdaki örnek, bir görevin tamamlanmasını beklemek için iptal belirtecinin basit kullanımını gösterir.The following example illustrates the simple use of a cancellation token to cancel waiting for a task's completion. Bir görev başlatılır, CancellationTokenSource.Cancel belirteç kaynağının iptal belirteçlerini iptal etmek için yöntemini çağırır ve sonra beş saniye geciktir.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. Görevin kendisine iptal belirtecini geçirmediğini ve iptal edilemez olduğunu unutmayın.Note that the task itself has not been passed the cancellation token and is not cancelable. Uygulama iş parçacığı, Task.Wait görevin tamamlanmasını beklemek için görevin yöntemini çağırır, ancak iptal belirteci iptal edildiğinde ve bir durum oluşturulduktan sonra bekleme iptal edilir OperationCanceledException .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. Özel durum işleyicisi özel durumu raporlar ve sonra altı saniye boyunca uyku moduna geçer.The exception handler reports the exception and then sleeps for six seconds. Örneğin çıkışının gösterdiği gibi, bu gecikme görevin durumunda tamamlanmasını sağlar RanToCompletion .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

Açıklamalar

Wait(CancellationToken)Yöntemi bir iptal edilebilen bekleme işlemi oluşturur; diğer bir deyişle, aşağıdakilerden biri gerçekleşene kadar geçerli iş parçacığının beklemesini sağlar:The Wait(CancellationToken) method creates a cancelable wait; that is, it causes the current thread to wait until one of the following occurs:

Not

İptal belirtecinin iptal edilmesi, cancellationToken aynı zamanda iptal belirtecini geçirmediği ve iptali işlemeye hazırlanmadığı takdirde, çalışan görev üzerinde hiçbir etkiye sahip değildir.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. cancellationTokenNesnenin bu yönteme geçirilmesi yalnızca bekleme işleminin iptal edilmesine izin verir.Passing the cancellationToken object to this method simply allows the wait to be canceled.

Şunlara uygulanır

Wait()

TaskÇalışmasının tamamlanmasını bekler.Waits for the Task to complete execution.

public:
 void Wait();
public void Wait ();
member this.Wait : unit -> unit
Public Sub Wait ()

Özel durumlar

TaskAtıldı.The Task has been disposed.

Görev iptal edildi.The task was canceled. InnerExceptionsKoleksiyon bir nesne içeriyor TaskCanceledException .The InnerExceptions collection contains a TaskCanceledException object.

-veya--or- Görevin yürütülmesi sırasında bir özel durum oluştu.An exception was thrown during the execution of the task. InnerExceptionsKoleksiyon, özel durum veya özel durumlar hakkında bilgiler içerir.The InnerExceptions collection contains information about the exception or exceptions.

Örnekler

Aşağıdaki örnek 0 ile 100 arasında 1.000.000 rastgele tamsayılar üreten ve bunların Ortalama değerlerini hesaplayan bir görevi başlatır.The following example starts a task that generates one million random integers between 0 and 100 and computes their mean. Örnek, Wait uygulamanın sonlandırmadan önce görevin tamamlanmasını sağlamak için yöntemini kullanır.The example uses the Wait method to ensure that the task completes before the application terminates. Aksi takdirde, bu bir konsol uygulaması olduğundan, görev hesaplama ve ortalama değeri görüntülemeden önce Bu örnek sonlandırılır.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

Açıklamalar

Wait , çağıran iş parçacığının geçerli görev tamamlanana kadar beklemesini sağlayan bir eşitleme yöntemidir.Wait is a synchronization method that causes the calling thread to wait until the current task has completed. Geçerli görev yürütmeyi başlatmadığından, bekleme yöntemi görevi Scheduler 'dan kaldırmaya çalışır ve geçerli iş parçacığında satır içi olarak yürütülür.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. Bunu yapamadıysanız veya geçerli görev yürütmeyi zaten başlamışsa, görev tamamlanana kadar çağıran iş parçacığını engeller.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. Daha fazla bilgi için .NET blogu ile paralel programlamada Task. Wait ve "ıntıl" bölümüne bakın.For more information, see Task.Wait and "Inlining" in the Parallel Programming with .NET blog.

Şunlara uygulanır