首页 > 解决方案 > 如何在这种多线程情况下编写干净的代码?

问题描述

这段代码运行良好,但看起来很糟糕。在这种情况下如何编写漂亮的代码?

你可以在操场上看它: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)
    {

    }
}

标签: c#multithreading

解决方案


好吧,您可以为此尝试PLinqParallel Linq),并摆脱locks、Threads 等。

  using System.Linq;

  ...

  uidList
    .AsParallel()
    //.WithMergeOptions(ParallelMergeOptions.NotBuffered)
    //.AsOrdered()
    .ForAll(item => DoSomeJob(item));

推荐阅读