C#6等待完成任务和所有子任务

时间:2017-10-10 07:55:24

标签: .net multithreading asynchronous task taskscheduler

我试图建立一种调度程序(这可能不是相关术语),它将按顺序运行许多任务。

这是我的POC代码(请忽略队列/出队机制哪个很差,但我猜这里不是问题)

编辑:感谢@Theraot

的帮助
    static void Main(string[] args)
    {
        ProcessingQueue o_q = new ProcessingQueue();
        o_q.Enqueue(async () => { await SimulateTaskSequence(1); });
        o_q.Enqueue(async () => { await SimulateTaskSequence(2); });

        Console.ReadLine();
    }

    public static async Task SimulateTaskSequence(int taskNbr)
    {
        Console.WriteLine("T{0} - Working 1sec", taskNbr);
        Thread.Sleep(1000);

        Console.WriteLine("T{0} - Zzz 1st 1sec", taskNbr);
        await Task.Delay(1000);

        Console.WriteLine("T{0} - Working 1sec", taskNbr);
        Thread.Sleep(1000);

        Console.WriteLine("T{0} - Done", taskNbr);
    }

    public class ProcessingQueue
    {
        Queue<Action> _Queue = new Queue<Action>();
        private bool _stillRunning = false;

        public void Enqueue(Action a)
        {
            lock (_Queue)
            {
                _Queue.Enqueue(a);

                if (_stillRunning == false)
                {
                    StartProcessing();
                }
            }
        }


        private void StartProcessing()
        {
            _stillRunning = true;

            Task.Run(async () =>
            {
                Action a = null;

                while (true)
                {
                    lock (_Queue)
                    {
                        if (_Queue.Any() == true)
                        {
                            a = _Queue.Dequeue();
                        }
                        else
                        {
                            break;
                        }
                    }

                    await Task.Run(a); //how to wait for all subtasks!!???
                }
                _stillRunning = false;
            });
        }

我的问题是,只要第一个任务(T1)发生第一次等待,第二个任务(T2)就会开始执行。

我得到以下输出:

T1 - Working 1sec
T1 - Zzz 1st 1sec
T2 - Working 1sec
T2 - Zzz 1st 1sec
T1 - Working 1sec
T1 - Done
T2 - Working 1sec
T2 - Done

但我期待的是:

T1 - Working 1sec
T1 - Zzz 1st 1sec
T1 - Working 1sec
T1 - Done
T2 - Working 1sec
T2 - Zzz 1st 1sec
T2 - Working 1sec
T2 - Done

我理解为什么这是默认行为,但我需要改变它。我在一个新的TaskFactory中玩TaskContinuationOptions和TaskCreationOptions,但没有更好的结果。 这甚至可能吗?

非常感谢 克里斯托夫

1 个答案:

答案 0 :(得分:2)

我建议您创建一个ProcessingQueue<Func<Task>>而不是ProcessingQueue<Action>

public class ProcessingQueue
{
    Queue<Func<Task>> _Queue = new Queue<Func<Task>>();

    private bool _stillRunning = false;

    public void Enqueue(Func<Task> a)
    {
        lock (_Queue)
        {
            _Queue.Enqueue(a);

            if (_stillRunning == false)
            {
                StartProcessing();
            }
        }
    }

    private void StartProcessing()
    {
        _stillRunning = true;

        Task.Run(async () =>
        {
            Func<Task> a = null;

            while (true)
            {
                lock (_Queue)
                {
                    if (_Queue.Any() == true)
                    {
                        a = _Queue.Dequeue();
                    }
                    else
                    {
                        break;
                    }
                }

                await a(); //how to wait for all subtasks!!???
            }
            _stillRunning = false;
        });
    }

<强>解释

在有问题的代码中,

Action a;
...
await Task.Run(a);

您正在执行Task.Run(Action action),因为操作可能包含异步任务,Run方法无法等待任务,因为没有任务。当您致电Task.Run(Func<Task> task) Run时,方法知道它是任务,它将等待它,