同时进行C#Timer 2动作

时间:2011-08-12 12:28:34

标签: c# multithreading concurrency

任何人都可以帮助转换/提供如何将下面的代码转换为同时运行的两个函数的框架,这两个函数都有自己独立的计时器。

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());
}

显然上面的内容永远不会有效,但主要是一个方法每1秒运行一次,将一些数据添加到列表中。

另一个操作也在一个计时器上运行,并接受可能在此列表中的任何内容并对其执行某些操作,然后清除列表。 (在我这样做时,不要担心列表的内容会发生变化)。我已经阅读了大量的教程和示例,但很简单,我不知道如何解决这个问题。任何想法/提示?

1 个答案:

答案 0 :(得分:3)

要在间隔时间内同时运行两个操作,您可以使用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           
    }
}

在您的问题的上下文中,共享状态将是您要在两个操作中操作的列表:totRand