C#定时器2同时动作

C#定时器2同时动作,c#,multithreading,concurrency,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

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

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());
}
public void Controller()
{
List totRand=新列表();
做
{
睡眠(新的时间跨度(0,0,0,1));
添加(ActionA());
}虽然(正确);
做
{
睡眠(新的时间跨度(0,0,0,30));
行动B(托特兰);
totRand=新列表();
}虽然(正确);
}
公共行动a(
{
随机r=新随机();
返回r.Next();
}
公共无效行动B(名单汇总)
{
int-total=0;
//总计=总计所有整数
Console.WriteLine(total/totRand.Count());
}
显然,上述方法永远不会起作用,但其原理是每1秒运行一个方法,将一些数据添加到列表中


另一个操作也会在计时器上运行,获取列表中的任何内容并对其执行操作,然后清除列表。(在我这样做时,不用担心列表的内容会发生变化)。我已经阅读了大量的教程和示例,但我根本不知道该怎么做。有什么想法/提示吗?

要在您可以使用的时间间隔内同时运行两个操作

专用只读计时器\u timerA;
专用只读定时器_timerB;
//这用于保护您将从ActionA和ActionB访问的字段
私有只读对象_sharedStateGuard=新对象();
私有只读列表_totRand=new List();
公共空间控制器(){
_timerA=新计时器(ActionA,null,TimeSpan.Zero,TimeSpan.FromSeconds(30));
_timerB=新计时器(ActionB,null,TimeSpan.Zero,TimeSpan.FromSeconds(1));
}
私有void ActionA(对象参数){
//要点:在此锁中包装使用共享状态的每个调用
锁(_sharedStateGuard){
//用这里的“totRand”列表做些什么
}
}
私有无效操作B(对象参数){
//要点:在此锁中包装使用共享状态的每个调用
锁(_sharedStateGuard){
//用这里的“totRand”列表做些什么
}
}

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

该.NET库包含3个或4个计时器类。您使用的是哪一个?您知道快速连续使用默认构造函数创建多个
Random
实例是错误的吗?每个线程创建一个实例并重用它。@CodeInChaos-只是一个小例子,实际上不会这样做,但谢谢:)
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           
    }
}