Answer the question
In order to leave comments, you need to log in
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;
}
}
Answer the question
In order to leave comments, you need to log in
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}");
}
Task t = Run();
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}");
});
return Task.Run(() =>
{
....
})
Run().Result;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question