如何在For循环中使用多线程

SAM*_*SAM 6 .net c# multithreading .net-2.0

我想达到以下要求; 请提出一些解决方案.

string[] filenames = Directory.GetFiles("C:\Temp"); //10 files

for (int i = 0; i < filenames.count; i++)    
{
    ProcessFile(filenames[i]); //it takes time to execute    
}
Run Code Online (Sandbox Code Playgroud)

我想实现多线程.例如,有10个文件.我想一次处理3个文件(比如可配置maxthreadcount).所以3个文件将在for循环的3个线程中处理,如果有任何线程完成执行,它应该从for循环中选择下一个项目.还希望确保在退出for循环之前处理所有文件.

请建议最好的方法.

yto*_*ano 17

尝试

Parallel.For(0, filenames.Length, i => {
    ProcessFile(filenames[i]);
});
Run Code Online (Sandbox Code Playgroud)

MSDN

它只能从.Net 4开始使用.希望可以接受.


Gre*_*mar 5

这将在 .net 2.0 中完成这项工作:

class Program
{

    static int workingCounter = 0;
    static int workingLimit = 10;
    static int processedCounter = 0;

    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles("C:\\Temp");
        int checkCount = files.Length;
        foreach (string file in files)
        {
            //wait for free limit...
            while (workingCounter >= workingLimit)
            {
                Thread.Sleep(100);
            }
            workingCounter += 1;
            ParameterizedThreadStart pts = new ParameterizedThreadStart(ProcessFile);
            Thread th = new Thread(pts);
            th.Start(file);
        }
        //wait for all threads to complete...
        while (processedCounter< checkCount)
        {
            Thread.Sleep(100);
        }
        Console.WriteLine("Work completed!");
    }

    static void ProcessFile(object file)
    {
        try
        {
            Console.WriteLine(DateTime.Now.ToString() + " recieved: " + file + " thread count is: " + workingCounter.ToString());
            //make some sleep for demo...
            Thread.Sleep(2000);
        }
        catch (Exception ex)
        {
            //handle your exception...
            string exMsg = ex.Message;
        }
        finally
        {
            Interlocked.Decrement(ref workingCounter);
            Interlocked.Increment(ref processedCounter);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 递减工作计数器存在一个问题 - 这不是原子操作。两个线程可能同时递减,并且计数器只会递减一次。最好使用 Interlocked.Decrement(refworkingCounter)。 (2认同)