如何等待完成任务及其继续?

时间:2017-01-10 07:31:48

标签: c# .net multithreading task

我学会了在书的基础上使用线程。

我想等待我的任务及其继续工作。但是我在“ BLEEEEEEEEEEEEEEEP ”之前看到“按任意键退出... ”消息(请查看我的代码的注释)。为什么会发生这种情况?如何解决?

我知道我可以使用两个任务并为每个任务使用Task.Wait(),但是如果我需要为延续对象做同样的事情呢?

enter image description here

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

namespace Bushman.Sandbox.Threads {
    class Program {
        static void Main(string[] args) {
            Console.Title = "Threads";

            try {
                // The main work
                Action act1 = () => {
                    for (int i = 0; i < 10; i++) {

                        int id = Thread.CurrentThread
                        .ManagedThreadId;

                        Console.WriteLine(
                            "bleep. Thread Id: {0}",
                            id.ToString());
                    }
                };

                // This operation is to be done when the main 
                // work will be finished.
                Action act2 = () => {

                    int id = Thread.CurrentThread
                        .ManagedThreadId;

                    Console.WriteLine(
                        "bleep. Thread Id: {0}",
                        id.ToString());

                    Console.WriteLine(
                        "BLEEEEEEEEEEEEEEEP. Thread Id: {0}",
                            id.ToString());
                };

                Task task = new Task(act1);
                var awaiter = task.GetAwaiter();
                awaiter.OnCompleted(act2);

                Console.WriteLine("Work started...");
                task.Start();

                // TODO: wait while both actions will be done

                task.Wait(); // it doesn't work as I expected

                // it doesn't work as I expected too...
                awaiter.GetResult();
            }
            catch (Exception ex) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }

            Console.WriteLine("Press any key for exit...");
            Console.ReadKey();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

OnCompleted事件在您不等待的其他线程上触发。您可以使用以下构造:

Task task = new Task(act1);
var awaiter = task.ContinueWith(x => act2()).GetAwaiter();
task.Start();

Console.WriteLine("Work started...");

awaiter.GetResult();

在这种情况下,act1将使用第一个任务执行,当此任务完成时,它将继续act2。在这种情况下,等待两者都将完成。