views:

73

answers:

6

A problem is that a particular resource cannot handle more than 1 request per second and I want to pass that parameter to a thread pool that manages all concurrent calls to that resource.

Is there any library that offers such kind of custom thread pool or I should look forward to implement my own?

Thanks.

A: 

If you have only one ressource then you could thing of an input thread that feeds the ressource. The input thread also could have an input queue where all "task producer" feed in thir requests or jobs. The thing between the threads could be blocking queue:

blocking Queue

schoetbi
+1  A: 

If you're using .NET 4, you can use a BlockingCollection<T> to accomplish this.

You can add your work items to the blocking collection from multiple threads in your application, then have a dedicated thread which calls GetConsumingEnumerable() to pull off items, and sleeps for the required time after processing each element to throttle to 1 request per second.

Reed Copsey
A: 

I'd spin off a thread, wrap it in a mutex, and force it to wait a second before releasing the lock. That way, in whatever process is generating these threads, each new thread will have to get in line before having access to the procedure.

The second thread will get spun off immediately, but will also immediately be queued because of the Mutex.

e.g.

{
Thread t = new Thread(()=>{DoSomething();}).Start();
Thread t2 = new Thread(()=>{DoSomething();}).Start();
}

private static Mutex _mutex = new Mutex();
private void DoSomething()
{
   _mutex.WaitOne();
   // Do Work
   Sleep(1000);
   _mutex.ReleaseMutex();
}

Optionally, if you really wanted to get specific, you could use the System.Diagnostics class to keep track of execution from start to finish of your procedure and make your Thread.Sleep only wait out the difference in execution time.

Kinda Hokey. =)

George
This works, but has the potential to cause a lot of blocking in the application. That may or may not be good... (probably not, though).
Reed Copsey
BTW - instead of a mutex, you could just lock on a private static object. That will be quite a bit lower overhead, and provide identical functionality. Mutex is very heavyweight in this case. Also, it'd be better to check start time, and sleep for 1000 ms - (now - startTime), if you want 1/second (this will do <1/second)
Reed Copsey
A: 

You could use Reactive Extensions from Microsoft Devlabs. There is a special Throttle operator that can limit the processing rate of an Observable.

Note that Reactive Extensions is not a final product, but you are free to use and distribute the library in its current form.

Albin Sunnanbo
A: 

Might want to check out Quartz.Net

qstarin
A: 

This is very similar to this question. I shamelessly recommend my answer.

P Daddy