I'm not sure if the following is possible, but I would like to invoke several actions in Paralell throttle, but to maintain the continuity of the processing flow without returning to the use of timers or sleep / sleep cycles.
So far I have worked on the fact that it loads a large batch of inputs from some source ... and then processes them in paralell in a controlled manner and loops, as shown below.
static void Main(string[] args)
{
while(true)
{
IEnumerable<int> inputs = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
RunAllActions(inputs, 3);
}
}
static void RunAllActions(IEnumerable<int> inputs, int maxConcurrency)
{
var options = new ParallelOptions() {MaxDegreeOfParallelism = maxConcurrency};
Parallel.ForEach<int>(inputs, options, DoWork);
Console.WriteLine("Batch of Work Done!!!");
}
static void DoWork(int input)
{
Console.WriteLine("Starting Task {0}", input);
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Finishing Task {0}", input);
}
what I would like to know is there a constructor in TPL that I could use to always work ... so that I can replace the "Timer Elapsing" and "Database Polling" with the MessageQueue Receieved event.
, ... , , , , , TPL.
internal class Engine
{
private MessageQueue mq;
private Queue<int> myInternalApplicationQueue;
public Engine()
{
mq = new MessageQueue();
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
myInternalApplicationQueue = new Queue<int>();
}
void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
int input = (int) e.Message.Body;
myInternalApplicationQueue.Enqueue(input);
}
public void StartWorking()
{
var options = new ParallelOptions() { MaxDegreeOfParallelism = 3 };
Parallel.KeepWorkingOnQueue<int>(myInternalApplicationQueue, options, DoWork);
}
}