JavaScript Queue function equivalent in C#
-
29-04-2021 - |
문제
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.
Here is the 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.
다른 팁
Here is the same code modified.. Work for me
if anyone can contribuete an thread safe version that will be great.
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();
}
}
}
제휴하지 않습니다 StackOverflow