Wednesday, August 27, 2014

Make multiple calls(tasks)

You could use a queue and a semaphore with 4 concurrent entries to implement this. Below is a simple console application that adds 50 phone numbers to a Queue<string> and then process them all by iterating the through the queue. Only 4 threads at a time can execute the code below the call to the WaitOne() method in the MakeCall method:



using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
public class Program
{
static readonly Queue<string> phoneNumbers = new Queue<string>();
static readonly Semaphore semaphore = new Semaphore(4, 4); //A semaphore that can satisfy up to four concurrent requests.
public static void Main()
{
// Populate the queue, i.e. add all phone numbers
for (int i = 0; i < 50; i++)
phoneNumbers.Enqueue(i.ToString());

// iterate through all phone numbers and make the calls
List<Task> tasks = new List<Task>();

do
{
string phoneNumber = phoneNumbers.Dequeue();
try
{
//MakeCall(phoneNumber);
tasks.Add(Task.Factory.StartNew(() => { MakeCall(phoneNumber); }));
}
catch (Exception)
{
//put the number back in the queue if the MakeCall method throws an exception...
phoneNumbers.Enqueue(phoneNumber);
}
}
while (phoneNumbers.Count > 0);

Task.WaitAll(tasks.ToArray());
semaphore.Dispose();
}

private static void MakeCall(string phoneNumber)
{
semaphore.WaitOne();

//call your server here...
Console.WriteLine(string.Format("calls {0} at {1}", phoneNumber, DateTime.Now.ToString("hh:mm:ss")));
System.Threading.Thread.Sleep(2000); //simulate that the call takes 2 seconds to complete...

semaphore.Release();
}
}
}


No comments:

Post a Comment