Can anyone help transform/provide a skeleton of how to transform the below code to both functions being running concurrently, both with their own separate timers.
public void Controller()
{
List<int> totRand = new List<int>();
do
{
Thread.Sleep(new TimeSpan(0,0,0,1));
totRand.Add(ActionA());
} while (true);
do
{
Thread.Sleep(new TimeSpan(0,0,0,30));
ActionB(totRand);
totRand = new List<int>();
} while (true);
}
public int ActionA()
{
Random r = new Random();
return r.Next();
}
public void ActionB(List<int> totRand)
{
int total = 0;
//total = add up all int's in totRand
Console.WriteLine(total / totRand.Count());
}
Obviously the above would never work, but the principal is that one method runs every 1 second, adds some data to a list.
Another action also runs on a timer and takes anything that may be in this list and does something with it, then clears the list. (not worrying about the contents of the list changing whilst i’m doing this). I’ve read plently of tutorials and examples but quite simply can’t get my head round how i’d go about this. Any ideas/hints?
To run two actions concurrently on interval you can use System.Threading.Timer
Shared state, in the context of your question, would be the list you want to manipulate in both actions:
totRand.