【问题标题】:C# 4.0 Tasks - Subclassing or Displaying Execution Tree?C# 4.0 任务 - 子类化或显示执行树?
【发布时间】:2010-10-04 17:01:44
【问题描述】:

您对我如何可视化任务树有什么建议吗?我将运行一大组长时间运行的任务,每个任务都有一些子任务,我想理想地在树/ DAG中将执行的运行可视化给用户。 如果可能的话,我想使用新的任务并行库

我的第一个想法是继承 Task 和 Name 和 description 字段,然后尝试查看 Task 是否具有获取子任务列表的属性。然后我可以使用 GraphSharp.codeplex.com 或类似的东西(任何偏好?)来可视化树。

有什么想法/建议吗?

谢谢

大卫

【问题讨论】:

    标签: c# .net c#-4.0 task


    【解决方案1】:

    就我个人而言,我会避免继承 Task(或 Task<T>)。这样做会导致 TaskFactory 无法正常运行,而且还可能导致失去灵活性或需要大量实现来覆盖所有功能。

    相反,我会创建一个课程来为您安排和开始任务。此类可用于生成所有任务(甚至只是使用工厂方法返回任务)。在内部,它可以轻松跟踪您的图形信息,使用构建任务的延续来跟踪完成或失败事件等。

    【讨论】:

    • 感谢 Reed,我创建了一个任务包装器,并使用带有 xaml 绑定的 Graph Sharp 将其可视化,以便在强制时更改任务的颜色 - 一切看起来都不错 :)
    【解决方案2】:

    下面的 dotnet 组件使我们能够在parent-child 关系中构造任务并允许我们有效地管理它。请参考以下链接,

    Octopus.TaskTree

    dotnet add package Octopus.TaskTree

    // ---------------
    // Create a structure of Tasks
    // ---------------
    IAsyncTask rootTask = new AsyncTask("root");
    
    IAsyncTask childTask_1 = new AsyncTask("Task-1");
    IAsyncTask childTask_2 = new AsyncTask("Task-2");
    
    rootTask.AddChild(childTask_1);
    rootTask.AddChild(childTask_2);
    
    // --------------
    // Set actions
    // --------------
    childTask_1.SetAction(async (reporter, cancellationToken) => {
        // Simple delay function.
        reporter.ReportProgress(TaskStatus.InProgress, 10, "Started...");
        await Task.Delay(1000);
        reporter.ReportProgress(TaskStatus.InProgress, 100, "Finished...");
    });
    
    childTask_2.SetAction(async (reporter, cancellationToken) => {
        // Simple delay function.
        reporter.ReportProgress(TaskStatus.InProgress, 5, "Started...");
        await Task.Delay(2500);
        reporter.ReportProgress(TaskStatus.InProgress, 100, "Finished...");
    });
    
    // Before starting the execution, you need to subscribe for progress report.
    rootTask.OnReporting += (sender, eventArgs) => {
        eventArgs.ProgressValue; // -> this will represent the overall progress
    };
    
    // Create and pass the cancellation token
    var tokenSource = new CancellationTokenSource();
    cancellationToken = tokenSource.Token;
    
    // Start the execution concurrently
    rootTask.ExecuteConcurrently(cancellationToken, true);
    
    // OR
    
    // Start the execution in series
    rootTask.ExecuteInSeries(cancellationToken, true);
    
    
    

    它提供了灵活性,您可以在根任务上await,以串行或并发方式启动子执行。你可以参考给定的代码 sn-p 可以让你清楚地了解组件的用途。

    【讨论】:

      猜你喜欢
      • 2018-02-03
      • 2018-01-25
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多