问题描述
在C#有没有使用委托做一些异步工作(调用的BeginInvoke()),并使用一个线程池的线程之间的区别如下图所示。
In C# is there any difference between using a delegate to do some work asynchronously (calling BeginInvoke()) and using a ThreadPool thread as shown below
public void asynchronousWork(object num)
{
//asynchronous work to be done
Console.WriteLine(num);
}
public void test()
{
Action<object> myCustomDelegate = this.asynchronousWork;
int x = 7;
//Using Delegate
myCustomDelegate.BeginInvoke(7, null, null);
//Using Threadpool
ThreadPool.QueueUserWorkItem(new WaitCallback(asynchronousWork), 7);
Thread.Sleep(2000);
}
编辑:结果
的BeginInvoke可以确保从线程池中的线程来执行异步代码,所以有什么区别呢?
BeginInvoke makes sure that a thread from the thread pool is used to execute the asynchronous code , so is there any difference?
推荐答案
乔达菲,在他的在Windows并发编程
书(页418)说,这大约 Delegate.BeginInvoke
:
Joe Duffy, in his Concurrent Programming on Windows
book (page 418), says this about Delegate.BeginInvoke
:
所有委托类型,按照约定提供旁边的普通同步一个BeginInvoke的和 EndInvoke会
方法调用
方法。虽然这是一个很好的编程模型的功能,你应该远离他们尽可能。实现使用其中规定一个相当大的开销,异步调用远程基础设施。队列工作线程池直接通常是一个更好的办法,尽管这意味着你要统筹自己会合逻辑。
编辑:我创建了相对开销以下简单的测试:
I created the following simple test of the relative overheads:
int counter = 0;
int iterations = 1000000;
Action d = () => { Interlocked.Increment(ref counter); };
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
for (int i = 0; i < iterations; i++)
{
var asyncResult = d.BeginInvoke(null, null);
}
do { } while(counter < iterations);
stopwatch.Stop();
Console.WriteLine("Took {0}ms", stopwatch.ElapsedMilliseconds);
Console.ReadLine();
在我的机器上面的测试在20秒左右运行。以
On my machine the above test runs in around 20 seconds. Replacing the BeginInvoke
call with
System.Threading.ThreadPool.QueueUserWorkItem(state =>
{
Interlocked.Increment(ref counter);
});
更改运行时间为864ms。
changes the running time to 864ms.
这篇关于在C#和delegate.BeginInvoke区别使用线程池线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!