Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

As mentioned in the comments, this is asking for trouble.

So, you need to have a thread-safe writer class:

public class FileWriter
{
    private ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim();
    public void WriteData(/*....whatever */)
    {
        lock_.EnterWriteLock();
        try
        {
            // write your data here
        }
        finally
        {
            lock_.ExitWriteLock();
        }
    }

} // eo class FileWriter

This is suitable for being called by many threads. BUT, there's a caveat. There may well be lock contention. I used a ReadWriterLockSlim class, because you may want to do read locks as well and hell, that class allows you to upgrade from a read state also.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...