A lot of API's are moving toward exposing only asynchronous methods. How much of a performance hit is there in scenarios where you have to immediately wait on these methods? Am I wrong in assuming that it causes the current thread to wait on a spawned thread to complete? Or does the CLR perform some sort of magic in these scenarios and make it all execute in the same thread?
许多API正朝着只暴露异步方法的方向发展。在必须立即等待这些方法的情况下,有多少性能影响?假设它导致当前线程在生成的线程上等待完成,我错了吗?或者CLR是否在这些场景中执行某种魔术并使它们在同一个线程中执行?
1 个解决方案
#1
3
By "asynchronous methods", I assume you mean Task<T>
based async methods.
通过“异步方法”,我假设你的意思是基于Task
So if you have a method that returns a Task<T>
and you immediately call its Wait()
method, that causes the current that to wait on an internal WaitHandle
object. The task most likely executes on a different thread and signals the WaitHandle
when completed, which releases the waiting thread. There is no compliler optimization that turns this scenario into a synchronous call that I'm aware of.
因此,如果您有一个返回Task
This is of course more work than just calling a synchronous equivalent of the async method. However,depending on your use case, it probably won't be a significant difference.
这当然比调用异步方法的同步等价物更有用。但是,根据您的使用情况,它可能不会有显着差异。
The more important question is why would you want to loose the advantages of async by blocking the calling thread? That is generally not a good idea, you should ensure you have a very good reason to do this.
更重要的问题是为什么要通过阻塞调用线程来放弃异步的优势?这通常不是一个好主意,你应该确保你有充分的理由这样做。
#1
3
By "asynchronous methods", I assume you mean Task<T>
based async methods.
通过“异步方法”,我假设你的意思是基于Task
So if you have a method that returns a Task<T>
and you immediately call its Wait()
method, that causes the current that to wait on an internal WaitHandle
object. The task most likely executes on a different thread and signals the WaitHandle
when completed, which releases the waiting thread. There is no compliler optimization that turns this scenario into a synchronous call that I'm aware of.
因此,如果您有一个返回Task
This is of course more work than just calling a synchronous equivalent of the async method. However,depending on your use case, it probably won't be a significant difference.
这当然比调用异步方法的同步等价物更有用。但是,根据您的使用情况,它可能不会有显着差异。
The more important question is why would you want to loose the advantages of async by blocking the calling thread? That is generally not a good idea, you should ensure you have a very good reason to do this.
更重要的问题是为什么要通过阻塞调用线程来放弃异步的优势?这通常不是一个好主意,你应该确保你有充分的理由这样做。