3

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?

Omer
  • 8,194
  • 13
  • 74
  • 92
  • 1
    http://stackoverflow.com/a/18015586/4767498 – M.kazem Akhgary Nov 04 '16 at 22:19
  • You can effectively only await a Task, which you need to create somehow. Whether it's Task.Run() or Task.Factory.StartNew(), or new Task() followed by task.Start(), you still need a Task if you want to await it. – sellotape Nov 04 '16 at 22:48
  • [Asynchrony is not threading](http://blog.stephencleary.com/2013/11/there-is-no-thread.html). – Dour High Arch Nov 04 '16 at 22:50
  • You can use `await` on any awaitable objects. E.g. there are many static methods of the `Task` class. See `TaskCompletionSource` class. There are a lot of `*Async` methods in different classes. All of them you can use with `await`. – Alexander Petrov Nov 04 '16 at 22:59

1 Answers1

2

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.

s3raph86
  • 556
  • 4
  • 17