简体   繁体   中英

Asynchronous Delegate Invocation (ADI) vs. Task Parallel Library (TPL)

I get this comment on ADI while reading Essential C# 4.0:

Unfortunately, the underlying technology used by the asynchronous delegate invocation pattern is an end-of-further-development technology for distributed programming known as remoting. And although Microsoft still supports the use of asynchronous delegate invocation and it will continue to function as it does today for the foreseeable future, the performance characteristics are suboptimal given other approaches—namely Thread, ThreadPool, and TPL. Therefore, developers should tend to favor one of these alternatives rather than implementing new development using the asynchronous delegate invocation API. Further discussion of the pattern is included in the Advanced Topic text that follows so that developers who encounter it will understand how it works.

So are there any limitations that ADI has and TPL doesn't, besides that TPL probably uses a not-end-of-further-development-yet technology?

Tasks and async delegates both use thread pool.

Tasks and async delegates are similar in the sense that exception can be propagated to caller. Tasks go one step further, accumulating all thrown exceptions and presenting them for all thread pool workers together.

Tasks allow for cancellation.

There's a free chapter that describes all of this in more detail: http://www.albahari.com/threading/

You ask for "limitations".

I don't think you will find anything that can't be done with ADI (also called APM). The point is performance and programmer effort.

The verdict seems unanimous, Joe Duffy also warns you away from the ADI/APM

And the conclusion is easy, use the TPL if you can. It is easy and efficient. And it's at the just-the -beginning-of-further-development point.

Not that I am an expert in TPL. From what I understand TPL abstracts the decisions on the level of parallelism as configurations/specification.

For instance, in a parallel for loop.

Parallel.For(0, 1000, a => Thread.Sleep(10000));

You don't necessarily spawn 1000 threads. The TPL will "parallelise" to the appropriate number of threads. As opposed to asynchronously invoking a method 1000 times. (Which won't create 1000 threads either, but you will just have blocked execution calls until the required resources are freed up.

Also, TPL allows you a higher level control of the parallel tasks. In the above example, you can pause/break/abort the for loop easily. Such as.

Parrallel.For(0, 1000, (a, loopState) => loopState.Break());

It's a bit of hassle to achieve the above using conventional async method invoke.

TL,DR: TPL are more efficient and easier to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM