Your One-Stop Solution to Learn C# Wait From Scratch

C# wait is called that as it waits for the task to finish its execution. Beginners will learn about Wait (TimeSpan), Wait (CancellationToken), Wait (Int32), Wait (Int32, CancellationToken), and Wait for overloads in this tutorial. All of these overloads with parameters, return types, and exceptions will be covered in this tutorial. Beginners will be able to learn all of these overloads through code examples. So, let's get started on this tutorial and try to understand everything about C#.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Introduction to C# Wait

C # wait is defined as waits for the task to finish its execution.

Namespace:

System.Threading.Tasks

Assembly:

System.Runtime.dll

  • It sources the current thread to wait until another thread calls its notify() or notifyAll() methods.
  • It must be invoked from a synchronized context, such as a block or method.
  • It means that the current thread must have a lock on the object before calling the Wait () method.
  • It releases the lock on the object on which it is called and adds it to the waitlist, allowing another thread to acquire the lock.

Overloads of C# Wait

C# wait has five overloads listed in the table below.

Overloads 

Description

Wait (TimeSpan)

It waits for the task to finish execution in a given time frame

Wait (CancellationToken)

The function that waits for the Task's execution to complete The Wait is terminated if a cancellation token is canceled prior to the task being completed.

Wait (Int32)

It waits for the task to finish execution in a specified number of milliseconds

Wait (Int32, CancellationToken)

The function that waits for the task to finish execution. If a timeout interval expires or a cancellation token is canceled before the task is completed, the wait is terminated.

Wait()

It waits for the task to finish running.

Next, you will go over each of these five c# wiat overloads in greater depth:

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

1. Wait(TimeSpan)

c#wait-overloads-1

Waits for the task to complete execution within a given time span.

Parameter

TimeSpan/timeout

A TimeSpan represents the number of milliseconds to wait, or -1 milliseconds to wait indefinitely.

Return Type

Boolean

Returns true if the Task was completed within the time limit; otherwise, false.

Exceptions 

  • ObjectDisposedException

The Task has been completed.

  • ArgumentOutOfRangeException

A timeout is a negative number other than -1 milliseconds, representing an infinite timeout that exceeds MaxValue.

  • AggregateException

The assignment was canceled. A TaskCanceledException object or An exception thrown during task execution can be found in the InnerExceptions collection. The information about the exception or exceptions is contained in the InnerExceptions collection.

Example

using System;

using System.Threading.Tasks;

public class timespan

{

   public static void Main()

   {

      Task t1 = Task.Run( () => {

                            Random r = new Random();

                            long sum1 = 0;

                            int n = 2000000;

                            for (int i = 1; i <= n; i++) {

                               int number = r.Next(0, 101);

                               sum1 += number;

                            }

                            Console.WriteLine("Total: {0:N0}", sum1);

                            Console.WriteLine("Mean: {0:N2}", sum1/n);

                            Console.WriteLine("N: {0:N0}", n);   

                         } );

     TimeSpan ts = TimeSpan.FromMilliseconds(120);

     if (! t1.Wait(ts))

        Console.WriteLine("timeout interval expires");

   }

}

The following example begins a task that generates two million random integers ranging from 0 to 100 and computes their mean. The Wait (TimeSpan) method is used in this example to wait for the application to finish within 120 milliseconds. If the application finishes normally, the task displays the sum and mean of the random numbers generated. If the timeout interval expires, the example displays a message before exiting.

Output 

c#wait-overloads-1code.

Key Points for Wait (TimeSpan)

Wait (TimeSpan) is a synchronization procedure that causes the calling thread to wait for the current task instance to finish until one of the following conditions is met:

  • The task is completed.
  • The Task is canceled, or an exception is thrown. You handle an AggregateException exception in this case. The AggregateException.InnerExceptions property holds information about the exception or exceptions.
  •  The timeout period has passed. In this case, the current thread resumes execution, and the method returns false.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

2. Wait (CancellationToken)

c#wait-overload-5.

The function that waits for the task to finish execution. If a cancellation token is canceled before the task is completed, the wait is terminated.

Parameter

cancellationToken

While waiting for the Task to finish, keep an eye out for a cancellation token.

Return Type

No Return Type

Exceptions 

  • OperationCanceledException

The cancellation token was deactivated.

  • ObjectDisposedException

The Task has been completed.

  • AggregateException

The assignment was canceled. A TaskCanceledException object or an exception thrown during task execution can be found in the InnerExceptions collection. The information about the exception or exceptions is contained in the InnerExceptions collection.

Example:

using System;

using System. Threading;

using System.Threading.Tasks;

public class cancel1

{

   public static void Main()

   {

      CancellationTokenSource cts = new CancellationTokenSource();

      Task t1 = Task.Run( () => { Console.WriteLine("Cancel");

                                 cts.Cancel();

                                 Task.Delay(2000).Wait();

                                 Console.WriteLine("Task ended delay");

                               });

      try {

         Console.WriteLine("wait for the task to complete");

         t1.Wait(cts.Token);

      }

      catch (OperationCanceledException e) {

         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",

                           e.GetType().Name, t1.Status);

         Thread.Sleep(3000);

         Console.WriteLine("After sleeping, the task status: {0:G}", t1.Status);

      }

      cts.Dispose();

   }

}

The following example manifests how to use a cancellation token to cancel waiting for a task to finish. The CancellationTokenSource is called when a task is launched. The cancel method is used to cancel any of the token source's cancellation tokens, followed by a two-second delay. It should be noted that the task has not been passed the cancellation token and thus is not cancelable. The application thread calls the task's task. 

The wait method is used to wait for the task to finish, but it is canceled once the cancellation token is canceled and an OperationCanceledException is thrown. The exception handler logs the exception and then sleeps for three seconds. As the example output demonstrates, the delay allows the task to be completed in the RanToCompletion state.

Output:

c#wait-overloads-2code

Key Points for Wait (CancellationToken)

Wait(CancellationToken) generates a cancelable wait, which causes the current thread to wait until one of the following events occurs:

  • The Task has been completed.
  • The cancellation token has been revoked. In this scenario, the call to the Wait (CancellationToken) method throws an OperationCanceledException.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

3. Wait (Int32)

wait-overloads-6.

Waits for the task to finish execution within a given number of milliseconds.

Parameter

milliseconds timeout Int32

The quantity of time to wait in milliseconds, or Infinite (-1) to wait indefinitely.

Return Type

Boolean

Returns true if the Task was completed within the time limit; otherwise, false.

Exceptions 

  • ObjectDisposedException

The Task has been completed.

  • ArgumentOutOfRangeException 

Millisecond's timeout is a negative number other than -1, which indicates an infinite timeout.

  • AggregateException

The assignment was canceled. A TaskCanceledException object or An exception thrown during task execution can be found in the InnerExceptions collection. The information about the exception or exceptions is contained in the InnerExceptions collection.

Examples: 

using System;

using System.Threading.Tasks;

public class iNT32

{

   public static void Main()

   {

      Task t1 = Task.Run( () => {

                            Random r = new Random();

                            long sum1 = 0;

                            int num = 2000000;

                            for (int ctr = 1; ctr <= num; ctr++) {

                               int number = r.Next(0, 101);

                               sum1 += number;

                            }

                            Console.WriteLine("total: {0:N0}", sum1);

                            Console.WriteLine("mean: {0:N2}", sum1/num);

                            Console.WriteLine("N: {0:N0}", num);   

                         } );

     if (! t1.Wait(120))

        Console.WriteLine("Timeout interval expires.");

   }

}


The following example begins a task that generates two million random integers ranging from 0 to 100 and computes their mean. The Wait (Int32) method is used in this example to wait for the application to finish within 120 milliseconds. If the application finishes normally, the task displays the sum and mean of the random numbers generated. If the timeout interval expires, the example displays a message before exiting.

Output:

c3wait-overloads-3

Key Points for Wait (int 32)

Wait (Int32) is a synchronization procedure that causes the calling thread to wait for the current task instance to finish until one of the following conditions is met:

  • The task is completed.
  • The task is canceled, or an exception is thrown. You handle an AggregateException exception in this case. The AggregateException.InnerExceptions property holds information about the exception or exceptions.
  • The millisecond's timeout interval has expired. The recent thread resumes execution, and the method returns false in this case.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

4. Wait (Int32, CancellationToken)

The function that waits for the task's execution to complete. The wait is terminated if a timeout interval expires or a cancellation token is canceled before the task is completed.

c#wait-overloads-2

Parameter

millisecondsTimeout \sInt32

The quantity of time to wait in milliseconds, or Infinite (-1) to wait indefinitely.

cancellationToken \sCancellationToken

While waiting for the Task to finish, keep an eye out for a cancellation token.

Return Type

Boolean 

Returns true if the Task was completed within the time limit; otherwise, false.

Exceptions 

  • OperationCanceledException

The cancellationToken was deactivated.

  • ObjectDisposedException

The task has been completed.

  • ArgumentOutOfRangeException

 Milliseconds timeout is a negative number other than -1, which indicates an infinite timeout.

  • AggregateException

The assignment was canceled. A TaskCanceledException object or An exception thrown during task execution can be found in the InnerExceptions collection. The information about the exception or exceptions is contained in the InnerExceptions collection.

Example:

using System;

using System. Threading;

using System.Threading.Tasks;

public class intcanc

{

   public static void Main()

   {

      CancellationTokenSource cts = new CancellationTokenSource();

      Thread thread1 = new Thread(CancelToken);

      thread1.Start(cts);

      Task t1 = Task.Run( () => { Task.Delay(2000).Wait();

                                 Console.WriteLine("Task ended delay");

                               });

      try {

         Console.WriteLine("About to wait completion of task {0}", t1.Id);

         bool result = t1.Wait(1210, cts.Token);

         Console.WriteLine("Wait completed normally: {0}", result);

         Console.WriteLine("The task status: {0:G}", t1.Status);

      }

      catch (OperationCanceledException e) {

         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",

                           e.GetType().Name, t1.Status);

         Thread.Sleep(3000);

         Console.WriteLine("After sleeping, the task status: {0:G}", t1.Status);

         cts.Dispose();

      }

   }

   private static void CancelToken(Object obj)

   {

      Thread.Sleep(1200);

      Console.WriteLine("Cancel the cancellation token from thread {0}...",

                        Thread.CurrentThread.ManagedThreadId);

      CancellationTokenSource source = obj as CancellationTokenSource;

      if (source != null) source.Cancel();

   }

}


The Wait (Int32, CancellationToken) method is used in the following example to provide both a timeout value and a cancellation token that can be used to end the wait for a task's completion. A new thread is started, and the CancelToken method is executed, which pauses before calling the CancellationTokenSource. To cancel the cancellation tokens, use the cancel method. The task is then launched after a 2-second delay. The wait procedure is then called to wait for the task's completion and is provided with both brief timeout merit and a cancellation token.

Output:

c#-wiat-3.

Key Points for Wait(Int 32, CancellationToken)

Wait (Int32, CancellationToken) is a synchronization method that causes the calling thread to wait for the current task instance to finish until one of the following conditions is met:

  • The task is completed.
  • The task is canceled, or an exception is thrown. You handle an AggregateException exception in this case. The AggregateException.InnerExceptions property holds information about the exception or exceptions.
  • The cancellationToken cancellation token has been deactivated. In this scenario, the call to the Wait(Int32, CancellationToken) method throws an OperationCanceledException.
  • The millisecond's timeout interval has expired. The contemporary thread resumes execution, and the method returns false in this case:

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

5. Wait()

Waits for the Task to finish running.

c#wait-overloads-4

Parameter 

No Parameter

Return Type

No Return Type

Exceptions:

  • ObjectDisposedException

The Task has been completed.

  • AggregateException

The assignment was canceled. A TaskCanceledException object or an exception thrown during task execution can be found in the InnerExceptions collection. The information about the exception or exceptions is contained in the InnerExceptions collection.

Example:

using System;

using System.Threading.Tasks;

public class wait1

{

   public static void Main()

   {

      Task t1 = Task.Run( () => {

                            Random r = new Random();

                            long sum1 = 0;

                            int num = 2000000;

                            for (int i = 1; i <= num; i++) {

                               int number = r.Next(0, 101);

                               sum1 += number;

                            }

                            Console.WriteLine("total: {0:N0}", sum1);

                            Console.WriteLine("mean: {0:N2}", sum1/num);

                            Console.WriteLine("number: {0:N0}", num);   

                         } );

     t1.Wait();

   }

}


The following example begins a task that generates two million random integers ranging from 0 to 100 and computes their mean. The wait method is used in this example to ensure that it completes the task before it terminates the application. Because this is a console application, the instance would end before the task could compute and display the mean.

Output:

c#wait-function-1

Key Points for Wait( )

The wait is a synchronization method that tells the calling thread to wait until the current task is finished. If the current task hasn't started yet, the wait method removes it from the scheduler and executes it inline on the current thread. If it is impotent to do so, or if the current task has already begun execution, it chunks the calling thread until the task is finished.

Now that you have reached the end of this c# wait tutorial, you’ll summarise everything you have learned so far.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Next Steps 

You learned what c# wait is in this c# wait. Following that, you looked at five different types of c# wait overloads:

  • Wait (time span).
  • Wait (cancellation token).
  • Wait (int 32).
  • Wait (cancellation token, int 32).
  • Wait (cancellation token, int 32).

You saw all of these overloads, along with their parameters, return types, and exceptions. Following that, you saw a code example of each overload with some key points.

If you want a complete study that goes beyond Mobile and Software Development, Simplilearn's Post Graduate Program in Full Stack Web Development will be ideal for you. This online coding Bootcamp, delivered in collaboration with Caltech CTME, covers the most in-demand programming languages and skills required for success in software development today. It's time to go out and explore.

Do you have any queries about this tutorial on the C# Wait? Please mention them in the comments section at the bottong of this page if you do. Our experts will be glad to reply to your questions as earliest as possible!

About the Author

Kartik MenonKartik Menon

Kartik is an experienced content strategist and an accomplished technology marketing specialist passionate about designing engaging user experiences with integrated marketing and communication solutions.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.