【发布时间】:2015-03-22 14:56:19
【问题描述】:
我认为这是一个非常多余的问题,但我确实深入挖掘并没有找到答案。我使用的是第一个提到的 here 非常愚蠢的例子。
我创建了一个 Windows 窗体应用程序,我在其中删除了主程序中的自动生成代码,并复制并粘贴了示例站点中的代码。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
//[STAThread]
static void Main()
{
// Create task and start it.
// ... Wait for it to complete.
Task task = new Task(ProcessDataAsync);
task.Start();
task.Wait();
}
static async void ProcessDataAsync()
{
// Start the HandleFile method.
Task<int> task = HandleFileAsync("D:\\test.txt");
// Control returns here before HandleFileAsync returns.
// ... Prompt the user.
Console.WriteLine("Please wait patiently " +
"while I do something important.");
// Wait for the HandleFile task to complete.
// ... Display its results.
int x = await task;
Console.WriteLine("Count: " + x);
}
static async Task<int> HandleFileAsync(string file)
{
Console.WriteLine("HandleFile enter");
int count = 0;
// Read in the specified file.
// ... Use async StreamReader method.
using (StreamReader reader = new StreamReader(file))
{
string v = await reader.ReadToEndAsync();
// ... Process the file data somehow.
count += v.Length;
// ... A slow-running computation.
// Dummy code.
for (int i = 0; i < 10000; i++)
{
int x = v.GetHashCode();
if (x == 0)
{
count--;
}
}
}
Console.WriteLine("HandleFile exit");
return count;
}
}
输出是:
HandleFile 进入 线程 0x8184 已退出,代码为 259 (0x103)。 线程 0x6764 已退出,代码为 259 (0x103)。 程序“[42112] testasyncforms.vshost.exe”已退出,代码为 0 (0x0)。 请耐心等待,我正在做重要的事情。
那么,为什么程序退出而不打印“HandleFile exit”?
【问题讨论】:
标签: c# asynchronous visual-studio-2013