使用线程避免过早的数据访问

Using threading to avoid too early data access

在我的 C# 程序中,我有一个自动的函数调用序列。它们按顺序调用,每个函数所需的数据取决于前任。所以每个函数都必须等待另一个函数完成。

不知道怎么回事,有些函数结果在下一个函数开始时不可用。

我尝试使用线程解决这个问题:

Task taskA = Task.Factory.StartNew(() => generateData());
taskA.Wait();

if(taskA.IsCompleted)
{ 
     System.Windows.MessageBox.Show("Generation has been completed.");
     Task taskB = Task.Factory.StartNew(() => Thread.SpinWait(100000));
     taskB.Wait();
}
else
     System.Windows.MessageBox.Show("Generation has NOT been completed.");

nextFunctionCall();

但不知何故,这不能正常工作。

以下函数在某个时候停止工作,并处于无限的 while 循环中。

我只是通过使用 at short timer 绕过了这个线程:

generateData();
Thread.SpinWait(1000000000);
nextFunctionCall();

当然这不是一个好的解决方案...

知道为什么线程不起作用吗?

我必须处置任务A吗?

谢谢

顺序机制;管道;或者可以使用 .NET 中的 TPL DataFlow 库来实现过滤器图。

MSDN:

The dataflow components build on the types and scheduling infrastructure of the TPL and integrate with the C#, Visual Basic, and F# language support for asynchronous programming. These dataflow components are useful when you have multiple operations that must communicate with one another asynchronously or when you want to process data as it becomes available. For example, consider an application that processes image data from a web camera. By using the dataflow model, the application can process image frames as they become available.

DataFlow 允许您将代码分解为专门用于特定操作的块。定义后,将块连接在一起。这取决于什么定义了 消息 在块之间传递以及何时传递。

DataFlow 让您可以完全控制每个块的并发级别以及块在给定时间可以操作的消息数。

在您的示例中,您可以定义一个名为 generateDataBlock 的块,即 "wired" 以将数据推送到 processing 块。