开发者

C# Timer 2 Actions Concurrently

开发者 https://www.devze.com 2023-03-27 21:40 出处:网络
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.

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

private readonly Timer _timerA;
private readonly Timer _timerB;

// this is used to protect fields that you will access from your ActionA and ActionB    
private readonly Object _sharedStateGuard = new Object();

private readonly List<int> _totRand = new List<int>();

public void Controller() {
    _timerA = new Timer(ActionA, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
    _timerB = new Timer(ActionB, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}

private void ActionA(object param) {
    // IMPORTANT: wrap every call that uses shared state in this lock
    lock(_sharedStateGuard) {
        // do something with 'totRand' list here           
    }
}

private void ActionB(object param) {
    // IMPORTANT: wrap every call that uses shared state in this lock
    lock(_sharedStateGuard) {
        // do something with 'totRand' list here           
    }
}

Shared state, in the context of your question, would be the list you want to manipulate in both actions: totRand.

0

精彩评论

暂无评论...
验证码 换一张
取 消