Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
2.0 kB
0
Indexable
Never
using System; 

using System.Collections.Concurrent; 

using System.IO; 

using System.Threading.Tasks; 

namespace ConcurrentTasks 

{ 

    class Program 

    { 

        static void Main(string[] args) 

        { 

            var inputFiles = new string[] { "input1.txt", "input2.txt", "input3.txt" }; 

            var outputFile = "output.txt"; 

            var inputQueue = new ConcurrentQueue<string>(); 

            foreach (var inputFile in inputFiles) 

            { 

                inputQueue.Enqueue(inputFile); 

            } 

  

            var tasks = new Task[Environment.ProcessorCount]; 

  

            using (var outputStream = new StreamWriter(outputFile)) 

            { 

                for (int i = 0; i < tasks.Length; i++) 

                { 

                    tasks[i] = Task.Factory.StartNew(() => 

                    { 

                        while (inputQueue.TryDequeue(out var inputFile)) 

                        { 

                            Console.WriteLine($"Reading {inputFile} from thread {Task.CurrentId}"); 

                            using (var inputStream = new StreamReader(inputFile)) 

                            { 

                                string line; 

                                while ((line = inputStream.ReadLine()) != null) 

                                { 

                                    Console.WriteLine($"Writing line to output from thread {Task.CurrentId}"); 

                                    outputStream.WriteLine(line); 

                                } 

                            } 

                        } 

                    }); 

                } 

                Task.WaitAll(tasks); 

            } 

            Console.WriteLine($"Writing complete to {outputFile}"); 

            Console.ReadKey(); 

        } 

    } 

}