我想在完成几个同时运行的工作时运行下一个工作

时间:2015-01-04 14:14:41

标签: c#

我希望在完成多项同时运行的工作时运行下一步工作

我不能指望完成工作的顺序。

WorkA, WorkB, WorkC is running at the same time at different threads

每项工作完成后 code Manager.SetWorkState(Manager.WorkState)正在运行

Ex : WorkA is done
Manager.SetWorkState(Manager.WorkState) Manager.SetWorkState(Manager.WorkState.WorkAIsDone); 

class Manager
{

    public enum WorkState
    {
        WorkAIsDone = 0x1,
        WorkBIsDone = 0x2,
        WorkCIsDone = 0x4,
    }

        WorkState state;

    public void SetWorkState(WorkState newState)
    {
        state = state | newState;
        if (state == (WorkState.WorkAIsDone | WorkState.WorkBIsDone | WorkState.WorkCIsDone))
        {
            Run_NextWork();
        }
    }

    public void Run_NextWork() { ... }
}

这种情况是否有更有效的解决方案?

你对这个案子的解决方案是什么?

1 个答案:

答案 0 :(得分:3)

使用Task Parellel Library可以轻松解决此问题。 以下是一些pseudocode,但我希望你能得到这个想法

class Manager
{
    List<Task> _tasks;

    public Manager()
    {

        _tasks = new List<Task>();

        //assuming your 3 tasks are already started from somewhere, run fourth task 
        StartNewTask(Run_NextWork);
    }

    public void StartNewTask(Action action)
    {
        //WaitAll waits for all tasks in array to complete before continuing
        Task.WaitAll(_tasks.ToArray());
        var newTask = Task.Run(action);
    }

    public void Run_NextWork()
    {
    }
}