Hax
Hax

Reputation: 154

.Result operation doesn't block

I expect the following code to be blocked for almost 5 secs, but it is not. It immediately prints. Isn't Result operation blocking?

class Program
{
    static void Main()
    {
        // Return a value type with a lambda expression
        Task<int> task1 = Task<int>.Factory.StartNew(() => Task.Delay(5000).Id + 100);
        int i = task1.Result;
        Console.WriteLine(i);
    }
}

Upvotes: 0

Views: 140

Answers (2)

IllusiveBrian
IllusiveBrian

Reputation: 3204

To me ContinueWith seems more natural for what you're trying to do:

Task<int> t = Task.Delay(5000).ContinueWith(delayTask => delayTask.Id + 100);
Console.WriteLine(t.Result);

This will execute the delay task and then execute the lambda in ContinueWith after the delay is complete.

Upvotes: 0

Serg
Serg

Reputation: 4666

This code is not waiting for Delay to finish. It starts the delay and then return immediately Id+100. So, when the code reaches the Result operation, the task1 is almost always is in Completed state, so you get Result immediately.

You can try following to get desired behaviour

Task<int> task1 = Task.Run(async () => await Task.Delay(5000).Id + 100);
int i = task1.Result;

Or better, use await instead of Result everywhere

Task<int> task1 = Task.Run(async () => await Task.Delay(5000).Id + 100);
int i = await task1;

or even

int i = await Task.Delay(5000).Id + 100

(but I'm unsure here as you may have more logic inside the task in actual code)

Upvotes: 5

Related Questions