Функция Javascript Queue, как конвертировать в c # - PullRequest
0 голосов
/ 15 февраля 2012

У меня есть код 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") ;
    }()

Ответы [ 2 ]

0 голосов
/ 15 февраля 2012

Вот тот же модифицированный код. Работайте для меня
, если кто-нибудь может предоставить версию с защитой потоков, которая будет отличной.

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

}

0 голосов
/ 15 февраля 2012

Вот примерный перевод, с которого можно начать:

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

Обеспечение безопасности этого потока оставлено читателю в качестве упражнения.

...