views:

194

answers:

3

hi there,

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.

A: 

Well there are several ways to accomplish it.

You can either start a new thread:

 Thread thread = new Thread(new ParameterizedThreadStart(delegate //actually you better to use ThreadStart
 {
 //your code goes
 //for example:
 MessageBox.Show("Hello other worlds")
 }));

Though you will have to make sure that thread exits properly

Or use background worker:

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Hope that helps

nomail
Don't know why I can't comment on your post, but you can also try a queue. I actually think that it can be faster than constantly acquiring and then releasing resources. You can actually make several queues on separate threads that will round-robin and equalize the flow of info. Hopefully made myself clear.
nomail
+1  A: 

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.

Peter G.
Wouldn't this work against the premise of the OP that the intent is to dispatch very fast. The execution of the consumers doesn't matter to the producer. In such a case a Nagle's type of buffering might not be helpful isn't it ?
Gangadhar
"dispatch very fast" is ambiguous. A Nagle algorithm ensures reasonably low dispatch latency and very good thoughput. That's what I call fast dispatch though let's hear the OP.
Peter G.
A: 

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?

Rei Miyasaka