开发者

Fastest way to asynchronously execute a method?

i´m currently dealing with a problem where i have to dispatch hell a lot of functions to another thread to prevent the current function from blocking. now i wonder what the fastest way is to perform this task.

开发者_如何学运维

currently i´m stuck with

ThreadPool.UnsafeQueueUserWorkItem

as its slightly faster than the regular QueueUserWorkItem. however, i´m afraid that the threadpool may block this here. is there a faster way of dispatching a method call to another thread? i just wonder what the best practice is for such a task? unsafe code would be no problem as it i´s in a scenario where already a lot of interop is used. thanks j.


CLR(4) team recommends:

Task is now the preferred way to queue work to the thread pool.

Read CLR 4.0 ThreadPool Improvements: Part 1 and New and Improved CLR 4 Thread Pool Engine for detail information. In short, reasons are: local queues, threads reusing, work stealing. Basiclly for load balancing goal.

Extras:

I don't understand why it's not the answer (downvoted).

You wrote

i have to dispatch hell a lot of functions to another thread to prevent the current function from blocking"

I reply: Some TPL (exists for net35) 'blocks' (concurrent collections, spinning primitives etc) are designed specifically for highly concurrent access, with the focus on minimizing or eliminating blocking for efficient management of work. You can use those blocks as well (for ex. - BlockingCollection for your problem). TPL designed for creating and handling hundreds (or even thousands) of cpu/io-bound operations (tasks) with minimal overhead (or millions with the help of PLinq).

You asked:

i just wonder what the best practice is for such a task?

I've already answered: best practice - TPL (reasoned, not just my recommendation)


Inserting multiple or bigger items at once should reduce the overhead.

Edited after reading one of your comments:

I have experienced similar things. My usual remedy is not to dispatch every asynchronous request immediately but rather mimic what Nagle's Algorithm does for TCP.

Here, upon receiving a Request() you would dispatch it immediately only if no asynchronous work is pending. If asynchronous work is pending you would dispatch only if a certain number of milliseconds since the earliest non-dispatched Request has elapsed or a certain number of outstanding Request()s has accumulated.

This is an effective pattern to cut down overhead when getting frequent Request()s over which you have no control. Hope that helps.


Maybe you could throw all your dispatch requests into a List<> and wake up another background thread to make the calls to QueueUserWorkItem.

Am I understanding the problem correctly?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜