R
R
Rustem Sultanov2017-10-17 15:48:23
.NET
Rustem Sultanov, 2017-10-17 15:48:23

Why doesn't this example work with async await?

class Program
{
    static void Main(string[] args)
    {
        Task<int> t = Run();
        Console.WriteLine("Main");
        Console.ReadLine();
    }

    static async Task<int> Run()
    {
        Console.WriteLine("Hello from begining \"Run\" method");
        int num = 1000000000;
        long res = await new TaskFactory().StartNew(() => { return SumZeroToNum(num); });
        Console.WriteLine($"Result: {res}");
    }

    static long SumZeroToNum(int num)
    {
        long result = 0;
        for (int i = 0; i < num; i++)
        {
            result += i;
        }
        return result;
    }
}

When trying to compile this code, the studio throws error CS0161 for the Run method : not all code paths return a value.
In my understanding, after creating a task, control is returned to the Main method, i.e. returns Task. Then why does the error occur?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lvv85, 2017-10-17
@neroforse

Fix the Run method

static async Task Run()
    {
        Console.WriteLine("Hello from begining \"Run\" method");
        int num = 1000000000;
        long res = await new TaskFactory().StartNew(() => { return SumZeroToNum(num); });
        Console.WriteLine($"Result: {res}");
    }

and the line to call this method:
Task t = Run();

E
eRKa, 2017-10-17
@kttotto

You have several mistakes here.
First, you Run()indicated in the method signature that it returns an object of the type, Task,but you didn't return it. If you want it to return a task, then you need to create it

var task = new Task(() => async
{ 
  Console.WriteLine("Hello from begining \"Run\" method");
    int num = 1000000000;
    long res = await new TaskFactory().StartNew(() => { return SumZeroToNum(num); });
    Console.WriteLine($"Result: {res}");
});

and then return
But having done in the Main Run () method, you will only receive the task object, it will not be executed automatically for you. To do this, you will need to do t.Start();
If you want to call the method through async, then inside you need to do this
return Task.Run(() =>
{
    ....
})

Then it will be possible to run it asynchronously
Or synchronously
Run().Result;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question