c# - 如何在这种多线程情况下编写干净的代码?
问题描述
这段代码运行良好,但看起来很糟糕。在这种情况下如何编写漂亮的代码?
你可以在操场上看它:https ://dotnetfiddle.net/GUZni0
或以下代码:
using System;
using System.Collections.Generic;
using System.Threading;
public class Program
{
static object valueLocker = new Object();
static List<int> uidList;
static int takeuid = -1;
static int countThreads = 0;
public static void Main()
{
for (;;) {
Console.WriteLine("Hello World");
uidList = new List<int>();
uidList.Add(0);
uidList.Add(1);
uidList.Add(2);
uidList.Add(3);
uidList.Add(4);
countThreads = 0;
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(TakeUidThread);
thread.Start();
}
线程完成后,主线程每 0.5 秒检查一次并获取新的 uidList
while (countThreads < 10)
{
Thread.Sleep(500);
}
Console.WriteLine("All threads finished");
}
}
public static void TakeUidThread()
{
var localuid = -1;
while (localuid < uidList.Count)
{
// thread takes free uid
lock (valueLocker)
{
takeuid++;
localuid = takeuid;
}
if (localuid < uidList.Count && localuid != -1)
{
DoSomeJob(uidList[localuid]);
}
}
Thread inc countThreads at end
lock (valueLocker)
{
countThreads++;
}
}
private static void DoSomeJob(int uid)
{
}
}
解决方案
好吧,您可以为此尝试PLinq(Parallel Linq),并摆脱lock
s、Thread
s 等。
using System.Linq;
...
uidList
.AsParallel()
//.WithMergeOptions(ParallelMergeOptions.NotBuffered)
//.AsOrdered()
.ForAll(item => DoSomeJob(item));
推荐阅读
- css - PrimeNG 使用 inputStyleClass 自动完成
- razor - Umbraco 7.12:如果 X 匹配当前页面 ID,或任何当前页面的后代 - 有可能吗?
- android - 如何对 ArrayList 进行排序
- reactjs - 使用 TypeScript 加载 SVG 文件
- python - 使用pycharm在python中输入提示
- vim - 如何从 Vim 的 match() 函数中删除颜色高亮
- excel - 无法在 mac 中使用 vba 更改按钮颜色
- reactjs - webpack 3 sass-loader 无法导入没有相对路径的 scss 文件
- c# - 尝试从 Visual Studio 2017 在本地运行 Azure Function App 会出现“func.exe 不存在”错误
- r - 将字体大小调整为绘图设备的大小