SoulRider
SoulRider

Reputation: 73

Clarification on C# Threading Tasks

I am using the C# threading tasks instruction from Microsoft here.

They state at the end:

The Result property blocks the calling thread until the task finishes.

Am I right in thinking this is just creating a thread for a function, but still holding up the main thread, and the progression of the calling function, as if it was running through a standard function call?

As a 2nd question, following on from my possibly incorrect first assumption, if I modified the code in the example to:

using System;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Return a value type with a lambda expression
        Task<int> task1 = Task<int>.Factory.StartNew(() => 1);            

        // Return a named reference type with a multi-line statement lambda.
        Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
        {
            string s = ".NET";
            double d = 4.0;
            return new Test { Name = s, Number = d };
        });

        int i = task1.Result;
        Test test = task2.Result;    
    }
}

Would it create and run both threads simultaneously, running through the functions before returning the tasks? Or will it progress through the threads one a time as I assumed originally?

Upvotes: 2

Views: 240

Answers (1)

hnefatl
hnefatl

Reputation: 6037

You're right, the Microsoft example will essentially call those functions synchronously:

...
Task<int> task1 = Task<int>.Factory.StartNew(() => 1);
int i = task1.Result;

Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
{
    string s = ".NET";
    double d = 4.0;
    return new Test { Name = s, Number = d };
});
Test test = task2.Result;
...

task1 will be started in a new thread, then the current thread will block until it returns its result. Then task2 will start in a a new thread...

For your example, they'll run at the same time. task1 is spawned, then task2, then the main thread waits for task1's result and then for task2's result.

Upvotes: 2

Related Questions