Created
January 14, 2016 22:16
-
-
Save amithegde/e3a666eedecd6607aaaa to your computer and use it in GitHub Desktop.
calls a method n number of times a second
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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