コード例 #1
0
ファイル: denychildattach.cs プロジェクト: wzchua/docs
    static void Main(string[] args)
    {
        Contoso.Widget w = new Contoso.Widget();

        // Perform the same operation two times. The first time, the operation
        // is performed by using the default task creation options. The second
        // time, the operation is performed by using the DenyChildAttach option
        // in the parent task.

        Console.WriteLine("Demonstrating parent/child tasks with default options...");
        RunWidget(w, TaskCreationOptions.None);

        Console.WriteLine();

        Console.WriteLine("Demonstrating parent/child tasks with the DenyChildAttach option...");
        RunWidget(w, TaskCreationOptions.DenyChildAttach);
    }
コード例 #2
0
ファイル: denychildattach.cs プロジェクト: wzchua/docs
    static void RunWidget(Contoso.Widget widget,
                          TaskCreationOptions parentTaskOptions)
    {
        // Record the time required to run the parent
        // and child tasks.
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        Console.WriteLine("Starting widget as a background task...");

        // Run the widget task in the background.
        Task <Task> runWidget = Task.Factory.StartNew(() =>
        {
            Task widgetTask = widget.Run();

            // Perform other work while the task runs...
            Thread.Sleep(1000);

            return(widgetTask);
        }, parentTaskOptions);

        // Wait for the parent task to finish.
        Console.WriteLine("Waiting for parent task to finish...");
        runWidget.Wait();
        Console.WriteLine("Parent task has finished. Elapsed time is {0} ms.",
                          stopwatch.ElapsedMilliseconds);

        // Perform more work...
        Console.WriteLine("Performing more work on the main thread...");
        Thread.Sleep(2000);
        Console.WriteLine("Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds);

        // Wait for the child task to finish.
        Console.WriteLine("Waiting for child task to finish...");
        runWidget.Result.Wait();
        Console.WriteLine("Child task has finished. Elapsed time is {0} ms.",
                          stopwatch.ElapsedMilliseconds);
    }