Alex Rivera | Logout

How to write in a single file with multiple threads?

Asked 2011-11-07T10:14:03.010
14

I am creating Windows Application in C# in which I want to write in multiple files with multiple threads. I am getting data from different ports and there is one file associated with every port. Is it possible that creation of thread for every port and use the same thread again and again for writing data to respective file? Suppose I am getting data from ports 10000,10001,10002 and there are three files as 10000.txt, 10001.txt and 10002.txt. I have to create three threads for writing data to these three files respectively and I want to use these threads again and again. Is it possible? Please can you give a small sample of code if possible?

Edit
Report

1 Answer

4

You answers to other posts are somewhat out-of-line with your original question - it seems you want to write to one different file per thread.

The easy answer is.. just do it - the file system is thread-safe. The only snag may be performance with only one disk. Concurrently and rapidly writing small chunks of data to many files may result in a lot of disk-thrashing as the file system tries to cope with the distributed files/directories with only one rotor arm. Modern hard disks with large caches and clever controllers will mitigate this to some extent, but you may have an issue. Try it and see!

Your problems will be increased if you plan to continually create and destroy threads, open and close data files for every incoming network read. If you can possibly avoid this, do so.

If the disk cannot keep up, you could implement some clever 'lazy-writing' algorithm of your own to increase the size of the disk writes and so reduce the number, or buy an SSD, or both.

answered 2011-11-07T13:02:34.533

Your Answer