Skip to content

Instantly share code, notes, and snippets.

@amithegde
Created January 14, 2016 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amithegde/e3a666eedecd6607aaaa to your computer and use it in GitHub Desktop.
Save amithegde/e3a666eedecd6607aaaa to your computer and use it in GitHub Desktop.
calls a method n number of times a second
void Main()
{
//calls a method n number of times in a second. tps = transactions per second
var tasker = new Tasker(tps: 10, taskToRun: (x) => {Console.WriteLine("hello " + x);});
tasker.Start(TimeSpan.FromSeconds(1));
}
public class Tasker
{
private int Tps { get; set; }
private Action<string> TaskToRun { get; set; }
public int BatchCount { get { return 4; } }
public int TasksPerBatch { get {return Tps/ BatchCount; } }
public Tasker(int tps, Action<string> taskToRun)
{
this.Tps = tps;
this.TaskToRun = taskToRun;
}
public void Start(TimeSpan time)
{
BatchCount.Dump("batch count");
TasksPerBatch.Dump("tasks per batch");
for (int i = 0; i < time.Seconds; i++)
{
Task.Factory.StartNew(() => RunTasks(i));
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
private void RunTasks(int i)
{
for (int t = 0; t < BatchCount; t++)
{
Parallel.ForEach(GetTaskBatch(TasksPerBatch), new ParallelOptions { MaxDegreeOfParallelism = 3 }, (curAction) =>
{
curAction(t.ToString());
});
Thread.Sleep(TimeSpan.FromSeconds(1).Milliseconds/4);
}
}
private IList<Action<string>> GetTaskBatch(int batchSize)
{
var list = new List<Action<string>>();
for (int i = 0; i < batchSize; i++)
{
list.Add(TaskToRun);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment