Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Task.Run(()=> DoWorkAsync()) and new Thread(async()=> DoWorkAsync());

I recently came across some code which confused me heavily, I have always thought that you must use threads or Async tasks, not mix and match between them,

public async Task DoWork()
{
   Task.Delay(1000);
}

Now I saw code calling this like so:

public void Main()
{
    var thread = new Thread(async () => { await DoWorkAync(); })
                {
                    Priority = ThreadPriority.Highest,
                    IsBackground = true
                };
        // Start thread
        proccessThread.Start();
}

Now this magically seemed to NOT create a thread each time it was run, it seemed to be using the ThreadPool.

now what I am struggling to understand is the difference between the above and:

public void Main()
{
 var task = Task.Run(DoWorkASync);
}

From my testing, it seems that C# Thread has a different functionality when passing in an Async Expression vs the standard method on which to run>

like image 660
Zapnologica Avatar asked Oct 31 '25 23:10

Zapnologica


1 Answers

This construct:

var thread = new Thread(async () => { await DoWorkAync(); });
    // Start thread
proccessThread.Start();

Calls Thread constructor overload accepting ThreadStart delegate, and ThreadStart delegate is () => void. So you have this:

var thread = new Thread(StuffYourThreadExecutes);
thread.Start();   

static async void StuffYourThreadExecutes() {
    await DoWorkAsync();
}

So you start new thread and it runs the code until first asynchronous operation begins. Then thread exists. After that first asynchronous operation completes - the rest executes on whatever thread task scheduler providers (usually thread pool thread). Any exceptions which happen during this process cannot be observed.

For example if DoWorkAsync is something like:

static async Task DoWorkAsync(){
    await Task.Delay(1000);
}

Then thread starts and almost immediately exits, doing nothing useful.

Task.Run, when passing async delegate there, does what is stated in docs:

Queues the specified work to run on the thread pool and returns a proxy for the task

So whole operation just runs on thread pool thread without creating threads for nothing. You can observe exceptions by awaiting task returned by Task.Run.

like image 173
Evk Avatar answered Nov 03 '25 12:11

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!