【发布时间】:2017-04-21 21:02:55
【问题描述】:
我正在关注这个 MSDN Walkthrough - Walkthrough: Creating a Dataflow Pipeline。我创建了一个TransformBlock 并通过对其执行Post 来执行它。
// Process "The Adventurous Life of a Versatile Artist: Houdini"
// by Harry Houdini.
downloadString.Post("http://www.gutenberg.org/cache/epub/45370/pg45370.txt");
然后,我调用Complete 方法并有一个Console.WriteLine("Press a key to exit:"); 行。
这是完整的代码。在这个阶段你也可以在this commit on my github repo找到它。
using System;
using System.Net.Http;
using System.Threading.Tasks.Dataflow;
namespace Palindromes.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//
// Create members of the Pipeline
//
// Download the requested resource as a string
var downloadString = new TransformBlock<string, string>
( url =>
{
Console.WriteLine($"Downloading from {url}...");
string result = null;
using (var client = new HttpClient())
{
// Perform a synchronous call by calling .Result
var response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// read result synchronously by calling .Result
result = responseContent.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(result))
Console.WriteLine($"Downloaded {result.Length} characters...");
}
}
return result;
}
);
// Process "The Adventurous Life of a Versatile Artist: Houdini"
// by Harry Houdini.
downloadString.Post("http://www.gutenberg.org/cache/epub/45370/pg45370.txt");
downloadString.Complete();
Console.WriteLine("Press a key to exit:");
Console.ReadKey();
}
}
}
当我执行这个控制台应用程序时,我希望看到如下输出。
预期输出
Downloading from http://www.gutenberg.org/cache/epub/45370/pg45370.txt...
Downloaded 129393 characters...
Press a key to exit:
但这是实际输出。 (我已经运行了几次,出现了相同的Console.WriteLine 输出序列。
实际输出
Press a key to exit:
Downloading from http://www.gutenberg.org/cache/epub/45370/pg45370.txt...
Downloaded 129393 characters...
为什么在调用TransformBlock 的Console.WriteLines 之前执行Press a key to exit 行?
不应该首先调用TransformBlock 的Console.WriteLines,因为我首先调用它,因为这将成为管道的一部分?此外,据我所知,我没有任何 async 代码,而且我不完全了解 TPL 数据流 的内部工作原理,所以为什么这似乎是在执行订购?
谢谢!
【问题讨论】:
标签: c# async-await task-parallel-library tpl-dataflow