user3421896
user3421896

Reputation:

C#: is FileStream.ReadByte() a multi-threading friendly function?

So I have 16 threads that simultaneously run this method:

    private void Work()
    {
        int currentByte;
        char currentChar;

        try
        {
            while (true)
            {
                position++;
                currentByte = file.ReadByte();
                currentChar = Convert.ToChar(currentByte);

                entries.Add(new Entry(currentChar));
            }
        }
        catch (Exception) { }
    }

And then I have one more thread running this method:

    private void ManageThreads()
    {
        bool done;

        for(; ; )
        {
            done = !threads.Any(x => x.IsAlive == true);//Check if each thread is dead before continuing
            if (done)
                break;
            else
                Thread.Sleep(100);
        }
        PrintData();
    }

Here is the problem: the PrintData method just prints everything in the 'entries' list to a text file. This text file is different every time the program is run even with the same input file. I am a bit of a noob when it comes to multi-threaded applications so feel free to dish out the criticism.

Upvotes: 0

Views: 1259

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

In general unless type explicitly calls out thread safety in its documentation you should assume it is not thread-safe*. Streams in .Net do not have such section and should be treated non-thread safe - use appropriate synchronization (i.e. locks) that guarantees that each stream is accessed from one thread at a time.

With file streams there is another concern - OS level file object may be updated from other threads - FileStream tries to mitigate it by checking if its internal state matches OS state - see FileStream:remarks section on MSDN.

If you want thread safe stream you can try to use Synchronized method as shown in C#, is there such a thing as a "thread-safe" stream?.

Note that code you have in the post will produce random results whether stream is thread safe or not. Thread safety of a stream will only guarantee that all bytes show up in output. If using non thread safe stream there is no guarantees at all and some bytes may show up multiple times, some skipped and any other behavior (crashes, partial reads,...) are possible.


* Thread-safe as in "internal state of the instance will be consistent whether it is called from one thread or multiple". It does not mean calling arbitrary methods from different threads will lead to useful behavior.

Upvotes: 3

Related Questions