简体   繁体   English

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

[英]Can I implement c# task asynchronous with java(type)script?

I'm just curious about doing asynchronous job with javascript or typescript .我只是对使用javascripttypescript进行异步工作感到好奇。
I made some program with C# and following is source that I wrote.我用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);
    }
}

below is capture image of result.下面是结果的捕获图像。
在此处输入图像描述

I can imagine that why console does write above result.我可以想象为什么控制台会写出上面的结果。

and following source is written in typescript.以下源代码是用 typescript 编写的。 I tried to simulate same result, but failed.我试图模拟相同的结果,但失败了。

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

below image is typescript one.下图是 typescript 之一。 在此处输入图像描述

can I get any advice for making same result with C# result in `java(type)script?我可以得到任何建议以使用C#结果在 `java(type)script 中产生相同的结果吗? I tried many times to implement, but many time I failed.我尝试了很多次来实现,但很多次我都失败了。
thank you for read.谢谢你的阅读。

JavaScript has only one thread in the same context, but the web browser APIs do not. JavaScript 在同一上下文中只有一个线程,但 web 浏览器 API 没有。 We also have the possibility of simulating parallelism by using the setTimeout function or, with some limitations, by using the real parallelism provided by WebWorkers.我们还可以使用 setTimeout function 来模拟并行性,或者在有一些限制的情况下,使用 WebWorkers 提供的真正并行性来模拟并行性。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM