Home > Development > TPL – Waiting For Tasks

TPL – Waiting For Tasks


You can run a task an wait until it completes by using the Wait() method on the individual Task objects.
You can specify a timeout to wait for so you do not wait indefinitely.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TPLTasks
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Tasks1();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public static void Tasks1()
        {
            Task t1 = Task.Factory.StartNew(() =>
                                               {
                                                   Console.WriteLine(Task.CurrentId);
                                               });

            Task t2 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine(Task.CurrentId);
            });

            Task t3 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine(Task.CurrentId);
            });

            t1.Wait();
            t2.Wait(1000);
            t3.Wait(TimeSpan.FromSeconds(1));

        }

    }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: