Is having a return type of Task enough to make a method run asynchronously?

后端 未结 3 1463
悲哀的现实
悲哀的现实 2020-12-12 07:46

I have a simple method that does a complicated string operation and returns the result. As you can see, the return type of this method is Task. Th

3条回答
  •  借酒劲吻你
    2020-12-12 08:39

    Just as you flagged as async the Main method to get an asynchronous method you need to flag the method as asynchronous with the async keyword, and make the result a Task.

    But in the framework Tasks are used for 2 related but different concepts, parallelization and asynchronous programming.

    What you are doing is use parallelization.

    So you are just running some synchronous code on a different thread.

    Based on your example i think what you need is to use parallelization, which can speed up some complex calculation or work by use many threads to work in parallel.

    The concept behind asynchronous code is to free the thread while you are waiting for external resources (like some data from a web service), to allow other work to be done in the meantime.

    So, if you need to do complex work with local resources it's better use tasks without async logic, instead when working with remote resources you can go for asynchronous operations.

提交回复
热议问题