Kruti Joshi
Kruti Joshi

Reputation: 536

Does using two Task.Run without await make them run in parallel?

I have just started dipping my toes in asynchronous programming. I tried to read a lot about Task.Run but I'm not clear on one question.

If I have to two continuous statements which use Task.Run, without await, will those two run in parallel?

Code example:

Task.Run(()=> function1);
Task.Run(()=> function2);

Since I want a non-blocking call, Parallel.Invoke is not an option. I also don't want to wait for the context, so awaiting on Task.Run wouldn't make sense. Is this a good approach for fire and forget?

Upvotes: 1

Views: 1664

Answers (3)

Luaan
Luaan

Reputation: 63772

It is possible that they will run in parallel, yes.

Of course, this assumes that there are resources that allow them to run in parallel - for example, that you have enough free threadpool threads, that you have multiple execution units, that they're not blocking on the same I/O...

Note that even though you don't await those tasks, it's usually useful to keep the Task references around - e.g. for error handling, completion notification etc. Purely fire and forget operations are rather rare.

Upvotes: 3

Vivek Nuna
Vivek Nuna

Reputation: 1

static void Main(string[] args)
    {
        Task.Run(() => function1());
        Task.Run(() => function2());
    }

    private static void function2()
    {
        //throw new NotImplementedException();
    }

    private static void function1()
    {
        while (true)
        {

        }
    }

just run this code with breakpoints, you will see both the methods will run asynchronously. But it all depends on ThreadPool scheduling.

Upvotes: 0

tym32167
tym32167

Reputation: 4881

There are no correct answer on this question. When you call Task.Run(..) - you pass your action to Thread Pool, which has own scheduler. That scheduler will decide when it will run your action. So, it can run several as parallel, but, sometimes not. If you really want to run something parallel, you should use Thread or something like Parallel Extensions.

Upd. To start separate thread you can use

var thread = new Thread((() => { /*...*/ }));
thread.Start();

BUT! Be aware that for short-time operations and when you have to run many tasks - use Threads is not a good choise. In that cases Task.Run - will better. In common, I suggest to use Threads only for long-running calculation actions.

Upvotes: -1

Related Questions