I have a slow function that processes some input. There will be peak minutes during the day when the function is called a lot. I don't want this to introduce lag on the consumer side. Hence instead of letting this function do its work and then return true I want the function to add the input to a queue and then return true. Then I want the queue to be processed in the background until it is empty.
Can you please advise me the best way to do this in C#?
Here is some example code that I have started to work with:
namespace WCFServiceWebRole1
{
public class Service1 : IService1
{
public bool SlowFunction(string input)
{
// Here is a slow function that processes input...
return true;
}
}
}
namespace WCFServiceWebRole1
{
public class Service1 : IService1
{
public bool SlowFunction(string input)
{
AddToQueue(input);
return true;
}
}
}
You can use the ConcurrentQueue
class in the System.Collections.Concurrent
namespace. Here's a link to its description on MSDN . It would make it pretty easy to implement a producer-consumer queue pattern.
Have your SlowFunction
methods call Enqueue
on the class, and then have a System.Timers.Timer
object run a method periodically that does TryDequeue
. You might alternatively use System.Threading.Timer
or a scheduled task hitting another service call if you have some really weird use case.
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.