gpt4 book ai didi

c# - 如何并发构建字符串?

转载 作者:行者123 更新时间:2023-11-30 21:37:42 24 4
gpt4 key购买 nike

在下面给出的MWE(Minimal Working Example)中,我配置

  • Simulator.CpuBoundOperation("red", 150)); 在线程池线程中以红色字体旋转 150 次。

  • Simulator.CpuBoundOperation("green", 550); 以绿色字体旋转 550 次。

我想获得一个 HTML 输出,其中包含一串线程 ID 以及交替的红绿数字,因为它们同时运行。

不幸的是,输出显示了不需要的结果,其中先打印所有绿色数字,然后打印所有红色数字。我尝试增加迭代次数,但效果不佳。

如何解决这个问题?

MWE

using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

static class Simulator
{
private static readonly StringBuilder sb = new StringBuilder();

static Simulator()
{
string begin = "<!DOCTYPE html><html><body style='width:500px;background-color:black;font-size:20pt'><p>";
sb.Append(begin);
}

public static void CpuBoundOperation(string color, int n = 50)
{
for (long i = 0; i < n; i++)
sb.Append($"<span style='color:{color}'>{Thread.CurrentThread.ManagedThreadId} </span>");
// a white space before </span> is important
}

public static new string ToString()
{
sb.Append("</p></body></html>");
return sb.ToString();
}
}

class Test
{

static async Task Main(string[] args)
{
await Work();
File.WriteAllText("output.html", Simulator.ToString());
}

static async Task Work()
{
Task t = Task.Run(() => Simulator.CpuBoundOperation("red", 150));
Simulator.CpuBoundOperation("green", 550);
await t;
Simulator.CpuBoundOperation("blue");
}
}

enter image description here

最佳答案

在主线程完成绿色数字之前,您的操作(显然)没有花费足够的时间让后台线程开始运行。

坦率地说,你很幸运,所有发生的事情都是在主线程等待时后台任务才开始。 StringBuilder 不是线程安全的,因此如果您 得到并发执行,您就会损坏 StringBuilder,最多产生完全错误的输出,并在最坏的情况下使程序崩溃。

不清楚为什么要交错文本,但如果这是一个要求,您应该在一个线程中这样做。无论如何,至少在示例程序中没有足够的工作来证明并发性。如果你真的想保证并发性,你必须添加逻辑让主线程在后台线程开始工作之前不开始工作,但这有点反模式,因为它违背了并发性的主要目的:最大化吞吐量计算。

关于c# - 如何并发构建字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987121/

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