如何在C#中处理/实现多个任务

时间:2017-10-14 11:32:16

标签: c# parallel-processing task

我有必须执行大型计算任务的项目列表,所以我实现了相同的跟随。 如果我在这里做错任何事,请告诉我。

{
    "MainList": [{
            "Name": "First item from root task",
            "Task": [{
                "SubTask1": "...",
                "SubTask2": "..."
            }]
        },
        {
            "Name": "Second item from root task",
            "Task": [{
                "SubTask1": "...",
                "SubTask2": "...",
                "SubTask3": "...",
                "SubTask4": "..."
            }]
        }
    ]
}

情境:

  1. 必须对列表中的每个项目执行大型计算任务,如T1。
  2. 完成任何任务后,必须对同一列表中的每个项目执行另一项任务(这必须在T1完成后执行) 并行必须执行“任务”中的所有子任务 属性。
  3. 请注意,步骤2中的任务都必须在第一个任务完成后执行,然后这两个任务都可以执行paralley。

    考虑到上述情况,我开发了如下代码:

    代码:

    List<Task<object>> mainFirstTaskList = new List<Task<object>>();
    List<Task<object>> mainSecondTaskList = new List<Task<object>>();
    List<Task> subTaskList = new List<Task>();
    foreach (var itm in MainList)
    {
        mainFirstTaskList.Add(Task.Factory.StartNew<object>(() =>
        {
            //Use "itm" from iteration
            //Perform big computational task on each item
            return resultFirstMainList;
        }));
    }
    while (mainFirstTaskList.Count > 0)
    {
        int finishedTask = Task.WaitAny(mainFirstTaskList.ToArray());   //waiting for any of the task to gets complete
        Task<object> t = mainFirstTaskList[finishedTask];
        var result = t.Result;
    
        //Perform Another Task on the same list
        mainSecondTaskList.Add(Task.Factory.StartNew<object>(() =>
        {
            //use result from first task completed
            //Perform big computational task on each item
            return resultSecondMainList;
        }));
    
        //Perform the task on sub item list
        subTaskList.Add(Task.Factory.StartNew<object>(() => 
        {
            //Have used Parallel.For to partition the sub task computation
            //And have added this Parallel.For inside another Task, as Parallel.For will partition the tasks on current thread
            Parallel.For(1, subItemIndex, i =>
            {
                //Perform big task computation
            });
        }));
    }
    
      

    如果我在这里做错任何事,请告诉我。

    提前致谢!!!

1 个答案:

答案 0 :(得分:0)

我想我大致明白你在做什么。您应该使用Microsoft的Reactive Framework来实现此目的。然后你可以这样做:

var query =
    from mainItem in MainList.ToObservable()
    from firstResult in Observable.Start(() => ProcessMainItem(mainItem))
    from secondResult in Observable.Start(() => ProcessFirstItem(firstResult))
    from subItem in secondResult.ToObservable()
    from result in Observable.Start(() => ProcessSubItem(subItem))
    select result;

IDisposable subscription =
    query
        .Subscribe(x =>
        {
            /* Process results as they are computed */
        });

每个计算都是并行完成的,结果汇总在最终结果中。

如果您想将所有中间结果组合在一起,您甚至可以拥有select new { mainItem, firstResult, secondResult, subItem, result };