C # - Live text feed from one thread to another

In stream "A" I want to read a very long file, and, as it happens, I want to send each new line to another stream "B", which will do -something- to them.

Basically, I don’t want to wait for the file to finish loading before I start processing the lines. (I definitely want 2 threads and the connection between them, I have never done this before, and I want to learn)

So how do I do this? Thread A must wait for thread B to finish processing the “current line” before thread A sends another line to Thread B. But this will not be effective; so what about the buffer in stream B? (to catch the lines)

In addition, please give an example of what methods I should use for this exchange of streaming streams, since I did not find / did not see useful examples.

Thank.

+3
source share
1 answer

First of all, it is not clear that two streams will be useful here. One thread reading one line at a time (which is pretty easy withStreamReader) , , . , , , , , . ( , , , , 1 .) , , , , . , .

, , , ...

BlockingCollection<string> . ( , .NET 4 . ... .NET 4 - .) :

string nextLine = myFileReader.ReadLine();
myBlockingCollection.Add(nextLine);

- :

while (true)
{
    string lineToProcess = myBlockingCollection.Take();
    ProcessLine(lineToProcess);
}

, , . Take , .

, , , - , . - . BlockingCollection<T> BoundedCapacity - , Add , , ' t, .

, , , . , , , .

, , , ( ), BlockingCollection<T> , . , , , , , , , , , , .

+4

Source: https://habr.com/ru/post/1777950/


All Articles