I would note that most of the answers did not read the sample code. It's not about creating a bunch of threads and writing to disk, it's about spawning a bunch of threads, and some are working on the new JavaScriptSerializer (). Serialize (saeed); and then write to disk!
This is important to note, because the longer this work requires more benefit, the easier it is to stream, making sure that the disk does not idle during the calculation.
Long and short due to the fact that you wrote simplified code, as others have explained:
- You create 90,000 threads - this is unnecessarily expensive!
- You lock all the work by doing this single threaded!
- Yes, without blocking, you get an exception ... this does not magically make locking a good idea from the idea of ββperformance - it just means that you have a wrong code.
A quick and easy way to get into threads - it's a little less dangerous (although you can still fill it up) - use a parallel task library. For instance:
using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace ConsoleApplication15 { class Program { const int FILE_COUNT = 9000; const int DATA_LENGTH = 100; static void Main(string[] args) { if (Directory.Exists(@"c:\Temp\")) Directory.Delete(@"c:\Temp\", true); Directory.CreateDirectory(@"c:\Temp\"); var watch = Stopwatch.StartNew(); for (int i = 0; i < FILE_COUNT; i++) { string data = new string(i.ToString()[0], DATA_LENGTH); File.AppendAllText(string.Format(@"c:\Temp\{0}.txt", i), data); } watch.Stop(); Console.WriteLine("Wrote 90,000 files single-threaded in {0}ms", watch.ElapsedMilliseconds); Directory.Delete(@"c:\Temp\", true); Directory.CreateDirectory(@"c:\Temp\"); watch = Stopwatch.StartNew(); Parallel.For(0, FILE_COUNT, i => { string data = new string(i.ToString()[0], DATA_LENGTH); File.AppendAllText(string.Format(@"c:\Temp\{0}.txt", i), data); }); watch.Stop(); Console.WriteLine("Wrote 90,000 files multi-threaded in {0}ms", watch.ElapsedMilliseconds); } } }
The single-threaded version starts after about 8.1 seconds, and the multi-threaded version works after about 3.8 seconds. Please note that my test values ββare different from yours.
While the default TPL settings are not always optimized for the script you're working on, they provide a much better foundation than starting 90,000 threads! You will also notice that in this case I do not need to do any locks and I do not have to handle the closure, because the API presented already handles this for me.