问题描述
我需要做的计算(我用.NET 4)高效(使用线程尽可能少的),异步方式。
一种方法是
I need efficient (using fewest threads possible) asynchronous way of doing computation (and I use .net 4).One way is to
ThreadPool.QueueUserWorkItem(f => job.DoWork());
job.Completed += (a, b) => {...} //Completed is event I fire when work is done
另一种可能性是实现异步方法,是的完成之前,C#5节,这基本上是叫的BeginInvoke
的委托。
The other possibility is to implement async method as is done prior to C# v.5, which is basically calling BeginInvoke
on a delegate.
我的问题是:是否有这两个比不同的语法等,因为它似乎的BeginInvoke
还使用从一个新的线程线程池之间的差异
?
My question is: is there a difference between these two other than different syntax, as it seems BeginInvoke
is also using a new thread from ThreadPool
?
顺便说一句:这是可能的定义和同一个线程调用者的异步调用的方法(如以JavaScript完成)(在C#的任何版本)?
As an aside: is it possible to define and call a method asynchronously on the same thread as the caller (as is done in javascript) (in any version of C#)?
推荐答案
Delegate.BeginInvoke
提出的方法是在线程池
。的的BeginInvoke
的好处是,你可以使用的IAsyncResult
,可用于监视异步调用的进展。它的兄弟的方法, EndInvoke会
,检索异步调用的结果。它可以被称为的BeginInvoke
之后的任何时间。如果直到它完成异步调用尚未完成, EndInvoke会
阻塞调用线程。
Delegate.BeginInvoke
puts that method at the ThreadPool
. The advantage of BeginInvoke
is that you can use the IAsyncResult
, which can be used to monitor the progress of the asynchronous call. Its 'brother' method, EndInvoke
, retrieves the results of the asynchronous call. It can be called any time after BeginInvoke
. If the asynchronous call has not completed, EndInvoke
blocks the calling thread until it completes.
请参阅:
这篇关于有ThreadPool.QueueUserWorkItem和委托的BeginInvoke之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!