ContinueWith() public method

public ContinueWith ( Action continuationAction, TaskContinuationOptions continuationOptions ) : Task
continuationAction Action
continuationOptions TaskContinuationOptions
return Task
コード例 #1
0
        static void Main(string[] args)
        {
            // Create Task and run to completion
            Task newTask = new Task(() => DoWork());

            newTask.Start();
            // Or for the above two calls just do one as:
            // Task newTask = Task.Run(() => DoWork());
            // newTask.Wait();
            newTask.Wait();

            // Returning a Value from a task
            Task <int> task = Task.Run(() =>
            {
                return(CalculateResult());
            });

            Console.WriteLine(task.Result);

            // Wait all tasks
            Task [] tasks = new Task[10];
            for (int i = 0; i < 10; i++)
            {
                int taskNum = i; // Set task number for lambda exprestion
                tasks[i] = Task.Run(() => DoWork(taskNum));
            }

            // Listing 1.14
            // Think of the following as a horse race:
            // WaitAll() ensures that all the horses have crossed the finish line
            // WaitAny() ensures the program continues as soon as the first horse has crossed the finish line
            // I can see the use here if someone makes a notification system where the game continues and notifies players when someone has won!
            // Task.WaitAny(tasks);
            Task.WaitAll(tasks);

            // Listing 1.15
            // Continue task and the concept of an antecedant task.
            Task task2 = Task.Run(() => HelloTask());

            task2.ContinueWith((prevTask) => WorldTask());

            // Listing 1.16
            // Continuation Options
            Task task3 = Task.Run(() => HelloTask());

            task3.ContinueWith((prevTask) => WorldTask(), TaskContinuationOptions.OnlyOnRanToCompletion);
            // task3.ContinueWith((prevTask) => ExceptionTask(), TaskContinuationOptions.OnlyOnFaulted);

            // Listing 1.17
            // Child tasks - Not completed until the parent task ic complete and they are refereed to as detached child tasks
            // or detached nested tasks...
            // Tasks are created by calling the StartNew Method on the default Task.Factory
            // This can be created with TaskCreationOptions.DenyChildAttach options that deny it to be able to have attached children
            var parent = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Parent Starts");
                for (int i = 0; i < 10; i++)
                {
                    int taskNum = i;
                    Task.Factory.StartNew(
                        (x) => DoChild(x), // Lambda Expression
                        taskNum,           // state object
                        TaskCreationOptions.AttachedToParent
                        );
                }
            });

            parent.Wait(); // waits for all attached children to complete.


            // End Program
            Console.WriteLine("Finished Processing. Press a Key to end.");
            Console.ReadKey();
        }
コード例 #2
0
        static void Main(string[] args)
        {
            Task task1 = Task.Factory.StartNew(() => Console.WriteLine("Hello tasks"));

            Task task2 = Task.Run(() => Console.WriteLine("Hello tasks 2"));

            Console.WriteLine(task2.IsCompleted);
            task2.Wait();
            Console.WriteLine("task2 completed");

            Task task3 = new Task(() => Operation(1000));

            task3.Start();

            Task longTask = Task.Run(() => {
                Console.WriteLine("Start task...");
                Thread.Sleep(3000);
                Console.WriteLine("End task");
            });

            longTask.Wait(2000);
            Console.WriteLine("after wait...");

            Task longTask2 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(100);
                }
            },
                                                   TaskCreationOptions.LongRunning);

            List <Task> tasks = new List <Task>();

            for (int i = 1; i <= 5; i++)
            {
                int number = i;
                tasks.Add(Task.Run(() =>
                {
                    for (int j = 0; j < 10; j++)
                    {
                        Console.WriteLine("{0} {1}", number, new string('.', j));
                        Thread.Sleep(500);
                    }
                })
                          );
            }

            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("all tasks completed");

            //results
            Task <string> tsr = Task <string> .Run(() =>
            {
                return(DownloadHtml("http://www.microsoft.com"));
            });

            string str = tsr.Result;


            //continuation
            Task ts = Task.Run(() => Operation(1000)).ContinueWith((task) => Operation(2000));

            ts.Wait();

            Task taskRitardato = Task.Delay(5000).ContinueWith(task => Operation(1000));

            Task <string> webtask = Task <string> .Run(() =>
            {
                return(DownloadHtml("http://www.microsoft.com"));
            });

            Task <int> taskVocali = webtask.ContinueWith <int>(downloadTask =>
            {
                int count     = 0;
                string vocali = "aeiou";
                string result = downloadTask.Result;
                foreach (char ch in result)
                {
                    if (vocali.IndexOf(ch) > -1)
                    {
                        count++;
                    }
                }
                return(count);
            });

            Console.WriteLine(taskVocali.Result);

            Task[] taskArray = new Task[2];
            taskArray[0] = new Task(() => Operation(1000));
            taskArray[1] = new Task(() => Operation(2000));
            taskArray[0].Start();
            taskArray[1].Start();
            Task taskCont = Task.Factory.ContinueWhenAll(taskArray, (tasksPrecedenti) => Console.WriteLine("{0} Tasks completati", tasksPrecedenti.Count()));

            taskCont.Wait();

            taskArray[0] = new Task(() => Operation(1000));
            taskArray[1] = new Task(() => Operation(2000));
            taskArray[0].Start();
            taskArray[1].Start();
            Task <string> taskCont2 = Task.Factory.ContinueWhenAny <string>(taskArray, taskPrec => "uno dei task è terminato");

            Console.WriteLine(taskCont2.Result);

            Task[] task3Array = new Task[3] {
                new Task(() => Operation(1000)), new Task(() => Operation(3000)), new Task(() => Operation(2000))
            };
            foreach (var tsk in task3Array)
            {
                tsk.Start();
            }
            Task all3 = Task.WhenAll(task3Array);

            all3.Wait();
            Console.WriteLine("task3Array completed");

            Task <int> taskDiv = Task.Run <int>(() => Dividi(1, 0));

            try
            {
                int risultato = taskDiv.Result;
            }
            catch (AggregateException aggrEx)
            {
                if (taskDiv.IsFaulted)
                {
                    Console.WriteLine("il task è fallito");
                    Console.WriteLine(taskDiv.Exception.ToString());
                }
                else
                {
                    Console.WriteLine(aggrEx.InnerException.ToString());
                }
            }


            var cancelTokenSource   = new CancellationTokenSource();
            CancellationToken token = cancelTokenSource.Token;

            Task taskCancellable = Task.Run(() =>
            {
                token.ThrowIfCancellationRequested();

                for (int i = 0; i < 50; i++)
                {
                    Thread.Sleep(100);
                    if (token.IsCancellationRequested)
                    {
                        token.ThrowIfCancellationRequested();
                    }
                }
            }, token);

            try
            {
                cancelTokenSource.CancelAfter(1000);
                taskCancellable.Wait();
            }
            catch (AggregateException aggrEx)
            {
                if (taskCancellable.IsCanceled && taskCancellable.Status == TaskStatus.Canceled)
                {
                    Console.WriteLine(aggrEx.InnerException.ToString());
                }
            }


            Console.ReadLine();
        }