Confusion over .NET 4 Async

I am using the Microsoft.Bcl.Async nuget package to use Async / Await (my target is .NET 4, not 4.5).

I am new to Async / Await. My problem is described in the following code example. Why isn't the highlighted line called?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AsyncTest
{
class Program
{
    static void Main(string[] args)
    {
        Run();

        Console.WriteLine("Got the value");

        Console.ReadKey();
    }

    public static async void Run()
    {
        Console.WriteLine("Testing Async...");

        var val = await AsyncMethod();

        // HIGHLIGHTED LINE. WHY IS THIS LINE NOT CALLED?
        Console.WriteLine("And the value is... {0}", val);
    }

    public static Task<long> AsyncMethod()
    {
        long myVal = 1;

        for (long l = 0; l < 100000; l++)
        {
            myVal++;
            Console.WriteLine("l = {0}", l);
        }

        return new Task<long>(() => myVal);
    }
}
}

      

+3


source to share


2 answers


Line:

Console.WriteLine("And the value is... {0}", val);

      

converted (by the compiler) to a continuation; it will be called (with a value, etc.) only when the task that is "waiting" completes. The problem is that you create a task, but you haven't started it, so it will never finish.



If you run the task you create at the bottom, it will complete. Also, you usually do the "doing" work inside Task

- outside of it:

    public static Task<long> AsyncMethod()
    {
        var task = new Task<long>(() =>
        {
            long myVal = 1;

            for (long l = 0; l < 100000; l++)
            {
                myVal++;
                Console.WriteLine("l = {0}", l);
            }
            return myVal;
        });
        task.Start();
        return task;
    }

      

Also note that it Got the value

is printed long before And the value is...

- this is because the continuation is happening on the worker thread ; the method Run

returns control to the caller ( Main

) on the first await

.

+5


source


You shouldn't call it "AsyncMethod" because it has no asynchronous elements.



The method uses a task that will run in a separate thread from the current thread.

-1


source







All Articles