I have a JavaScript
code that I want to bring the idea into my C#
project.
This code brings multiple function call into a single management delayed call.
JavaScript
code: 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") ;
}()
Here's a rough translation to get you started:
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();
Making this thread-safe is left as an exercise for the reader.