gpt4 book ai didi

c# - 我可以用 java(type)script 异步实现 c# 任务吗?

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:59 25 4
gpt4 key购买 nike

我只是对使用 javascripttypescript 做异步工作感到好奇。
我用 C# 做了一些程序,下面是我写的源代码。

static void Main(string[] args)
{
var t1= Task.Run(() => { myFunc(0, ConsoleColor.Green); });
var t2 = Task.Run(() => { myFunc(50000, ConsoleColor.Red); });

t1.Wait();
t2.Wait();
}

static void myFunc(int number, ConsoleColor color)
{

for (int i = 0; i < 1e4; i++)
{
Console.ForegroundColor = color;
Console.WriteLine(number + i);
}
}

下面是截图结果。
enter image description here

我可以想象为什么控制台会写出上面的结果。

下面的源是用 typescript 写的。我试图模拟相同的结果,但失败了。

let i: number;
let j: string;
let k: number;
let mx: number =1e4;

function myFunc(offset: number, color: string) {

return new Promise(() => {

for (i = 0; i < mx; i++) {
console.log(color, i + offset);
}
});

};

async function myFunc2() {
const aa = myFunc(0, "\x1b[32m");
const bb = myFunc(50000, "\x1b[35m");
await aa;
await bb;

}

myFunc2();

下图是 typescript 。 enter image description here

对于使用 C# 在 `java(type)script 中产生相同的结果,我可以获得任何建议吗?我尝试了很多次实现,但很多次我都失败了。
感谢您阅读。

最佳答案

JavaScript 在同一上下文中只有一个线程,但 Web 浏览器 API 却没有。我们还可以通过使用 setTimeout 函数来模拟并行性,或者在有一些限制的情况下,通过使用 WebWorkers 提供的真实并行性来模拟并行性。

https://www.w3schools.com/jsref/met_win_settimeout.asp

https://www.w3schools.com/html/html5_webworkers.asp

关于c# - 我可以用 java(type)script 异步实现 c# 任务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58389342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com