0

我有一个JavaScript代码,我想将这个想法带入我的C#项目中。
此代码将多个函数调用带入单个管理延迟调用。

这是JavaScript代码:

  var ArgumentsCollection = [] ;
  var to_TimeOut = null ;

  function QueueWorkRunOnce(Argument) {
  clearTimeout(to_TimeOut);
  ArgumentsCollection.push(Argument) ;
        to_TimeOut = setTimeout(/* delegate */ function(){                  
            Worker(ArgumentsCollection); 
            //Reset ArgumentsCollection
            ArgumentsCollection = [] ;

        },/*Delay in ms*/ 1000 );
    }
    function Worker(Collection){
        alert(Collection.join(" ")) ;
    }

    onload = function(){
        QueueWorkRunOnce("Hi")
        //Some other stuff
        QueueWorkRunOnce("There")
        //Some other stuff
        QueueWorkRunOnce("Hello")
        QueueWorkRunOnce("World")

        //after Xms + 1000ms Will alert("Hi There Hello World") ;
    }()
4

2 回答 2

0

这是一个粗略的翻译,可以帮助您入门:

var worker = new Action<IEnumerable<string>>(collection =>
{
    Console.WriteLine(string.Join(" ", collection));
});

var args = new List<string>();
var timer = new Timer(state =>
{
    worker(args);
    //Reset args
    args.Clear();
});

var queueWorkRunOnce = new Action<string>(arg =>
{
    args.Add(arg);
    timer.Change(/*Delay in ms*/ 1000, Timeout.Infinite);
});

queueWorkRunOnce("Hi");
//Some other stuff
queueWorkRunOnce("There");
//Some other stuff
queueWorkRunOnce("Hello");
queueWorkRunOnce("World");

Console.ReadKey();

让这个线程安全留给读者练习。

于 2012-02-15T00:42:04.950 回答
0

这是修改后的相同代码。
如果有人可以贡献一个很棒的线程安全版本,请为我工作。

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace QueueWorkRunOnce {
public class Test {

    public static void worker(List<string> collection) {
        Console.WriteLine(string.Join(" ", collection.ToArray()));
    }

    public static List<string> args = new List<string>();

    public Timer timer = new Timer(state => {
        worker(args);
        args.Clear();
    });

    public void queueWorkRunOnce(string arg){
        args.Add(arg);
        timer.Change(/*Delay in ms*/ 1000, Timeout.Infinite);
    }

    public Test() {
        Console.WriteLine("new Test");

        queueWorkRunOnce("Hi");
        //Some other stuff
        queueWorkRunOnce("There");
        //Some other stuff
        queueWorkRunOnce("Hello");
        queueWorkRunOnce("World");           
    }
}
class Program {
    static void Main(string[] args) {
        new Test();
        Thread.Sleep(3000);
        new Test();
        Console.ReadKey();
    }
}

}

于 2012-02-15T10:23:11.913 回答