【问题标题】:Why program exits before async finishes its task?为什么程序在异步完成任务之前退出?
【发布时间】: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


    【解决方案1】:

    因为这个new Task(ProcessDataAsync); 不会做你想做的事。

    由于async void 模式仅用于异步事件处理,在您的情况下,我建议您通过ProcessDataAsync 方法返回Task,然后在该任务上简单地使用.Wait()

    【讨论】:

    • 我把它改成了这样“Task task = ProcessDataAsync();”我有一个例外:(
    • 也将 void 更改为 Task..但仍然是同样的问题给我“'System.InvalidOperationException' 类型的第一次机会异常”
    • Task task = ProcessDataAsync(); while static async Task ProcessDataAsync() 但是,您最好在这样做之前阅读一些文章。
    • 我也做了同样的事情,但仍然会产生无效操作的异常。我已经阅读了一些关于它的文章,我知道工作流程是如何进行的,但是这个虚拟的作品让我发疯了
    • @MohamedSalem 之后你不需要 .start。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多