c# - 如何让非必要的计算在后台运行?

标签 c# concurrency task-parallel-library .net-4.5

这个问题跟进Why is this code running synchronously? .我意识到我真正的问题比那篇文章中的问题更高层次。我现在在下面提出的问题是“我如何完成这个?”

我想在 C# 中使用并发来在后台计算事物。我有 ptsTin 类,它代表现有的地面。我想让加载速度尽可能快。有些工作是必不可少的,因为在工作完成之前您没有实例。例如,在 .LoadPoints() 和 .LoadTriangles 都完成之前没有 ptsTin 实例。

工作的其他部分不是必需的,可以稍后计算,即使稍后是 0.2 秒后。我想在一个新线程中开始非必要的工作,然后忘记它。如果它正在处理的值尚未准备好,则该值将为空。

这就是我想做的。代码现在在控制台应用程序中,但有一天会在 GUI 应用程序中。请注意,这是伪代码。我知道它不会像这样工作,它的目的是传达我想知道如何做的事情:

  static void Main(string[] args)
  {
      var myTin = ptsDTM.Load("SomeFile.ptsTin");
      // Do other stuff here like getElevationAtAPoint();
  }

  public static ptsTin Load(String file)
  {
     // Essential Work
     ptsTin newTin = new ptsTin();
     newTin.LoadPoints(file);
     newTin.LoadTriangles(file);

     // At this point I could return, but I want other stuff done
     // Non-essential work -- I want this on a "background" task
     newTin.BoundingBox = newTin.ComputeBBInTheBackground();    

     // Now return without waiting for ComputeBB to finish
     return newTin;
  }

如果稍后另一个方法请求 tin.BoundingBox,但该值尚未准备好,它仍然为 null。当它不为空时,其他方法将知道该值有效。

我该如何实现?

无论答案是使用异步和等待、Task.Run 还是任何其他方法,我都没有偏好。

最佳答案

How do I accomplish this?

您可以通过更改 BoundingBox 来做到这一点到 Task<BoundingBox>这将在未来完成。

public static ptsTin Load(String file)
{
    // Essential Work
    ptsTin newTin = new ptsTin();
    newTin.LoadPoints(file);
    newTin.LoadTriangles(file);

    // At this point I could return, but I want other stuff done
    // Non-essential work -- I want this on a "background" task
    newTin.BoundingBox = Task.Run(() => newTin.ComputeBB());

    // Now return without waiting for ComputeBB to finish
    return newTin;
}

现在,您可以通过其他方式查看状态:

if (ptsTin.BoundingBox.Status == TaskStatus.Completed)
{
     // Finished computing
}

关于c# - 如何让非必要的计算在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30033833/

相关文章:

c# - 在 ASP.net 网页中嵌入 Windows 窗体

c# - 在 C# 中创建仅适用于特定类型的通用函数

c# - 当线程等待到达锁定语句时记录

c - 多线程中的死锁

c# - 如何在 ASP.NET 中使用 Task 处理多个请求批处理?

c# - 使用 TPL 时不会引发异常

c# - DataGridView HeaderCell 为数字类型时不显示值

c# - SSL/TLS WCF 问题

java - 何时更喜欢 LinkedBlockingQueue 而不是 ArrayBlockingQueue?

api - 使用并发方法超时