Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You can use Task.Run to move CPU-bound work to a background thread [duplicate]

From the msdn,

You can use Task.Run to move CPU-bound work to a background thread.

My question is, are there any other options? If I want to use await keyword I must return Task and so I must use Task.Run

public static Task<int> LongProcess()
{
    return Task.Run<int>(() =>
    {
        //Long running 
        return 5;
    });
}

public async static void CallProcess()
{
    int a = await LongProcess();
}

Isn't above code only option to use await? If not, could you please show other options? If I don't use Task.Run, why do I need async/await?

like image 871
Omer Avatar asked Nov 27 '25 17:11

Omer


1 Answers

It's not just CPU intensive work. More usually you'll use async/await for I/O work that would otherwise lock the thread while waiting for a file system, database, or network operation to complete.

like image 137
s3raph86 Avatar answered Nov 30 '25 07:11

s3raph86



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!