I'm trying to understand the basics of asynchronous programming a little better, so I created the following snippet:
private void TaskContinuations()
{
Task<int> primeNumberTask = Task.Run(() =>
Enumerable.Range(2, 3000000)
.Count(n =>
Enumerable.Range(2, (int)Math.Sqrt(n) - 1)
.All(i => n % i > 0)));
var awaiter = primeNumberTask.GetAwaiter();
awaiter.OnCompleted(() =>
{
var result = awaiter.GetResult();
Console.WriteLine(result);
});
Console.Read();
}
I understand that I need to prevent the main UI task from stopping in order to prevent the background task from completing. Thus, it Console.Read();blocks the user interface thread, and if I do not hit the key before the tasks with a simple number are performed, the output in the console will be correct 216816. Everything is clear so far here.
, , Wait(); ( , OnCompleted) . , ( 1 2) , .
? ( , )
- /, ,
OnCompleted. , .
, - ?