0
votes

I see it as a very redundant question but i did really dig deep and didn't find answer.. I am using a very dummy example mentioned here, the first one.

I have created a windows form application where i removed the auto generated code in the main and i copied and past the code in the example site.

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;
    }
}

The output is:

HandleFile enter The thread 0x8184 has exited with code 259 (0x103). The thread 0x6764 has exited with code 259 (0x103). The program '[42112] testasyncforms.vshost.exe' has exited with code 0 (0x0). Please wait patiently while I do something important.

So, why program exits without printing "HandleFile exit"?

1

1 Answers

4
votes

Because this new Task(ProcessDataAsync); does not do what you want.

Since the async void pattern is used only for async event handling, in your case I would recomment you to return a Task by the ProcessDataAsync method and then simply .Wait() on that task.