Today, I took the time to learn the reactive extensions library. I thought it was easy to get started. I practiced it and wrote a readasync extension.
Static void main (string [] ARGs)
{
VaR buffersize = 1000;
VaR buffer = new byte [buffersize];
VaR stream = file. openread (@ "R: \ 1.txt ");
Stream. readasync (buffer). subscribe (
Onnext: I =>{ console. Write (encoding. Default. getstring (buffer, 0, I ));},
Oncompleted: () => console. writeline ("completed ")
);
Console. Readline ();
}
Public static iobservable <int> readasync (this stream, byte [] buffer)
{
VaR bufferlen = buffer. length;
VaR readasync = observable. fromasyncpattern <byte [], Int, Int, int> (stream. beginread, stream. endread );
Return observable. Defer () => readasync (buffer, 0, bufferlen). Repeat (). takewhile (I => I> 0)
// Return observable. While () => stream. Position! = Stream. length, observable. Defer () => readasync (buffer, 0, bufferlen )));
}
Public static iobservable <string> readlinesasync (this stream, byte [] buffer)
{
Return observable. createwithdisposable <string> (Observer =>
{
VaR blocks = stream. readasync (buffer). Select (I => encoding. Default. getstring (buffer, 0, I ));
VaR lastline = string. empty;
Return blocks. subscribe (Data =>
{
If (data. Contains ("\ r \ n "))
{
VaR lines = data. Split (New String [] {"\ r \ n"}, stringsplitoptions. None );
Observer. onnext (lastline + lines [0]);
Foreach (VAR line in lines. Skip (1). Take (lines. Length-2 ))
{
Observer. onnext (line );
}
Lastline = lines [lines. Length-1];
}
Else
{
Lastline + = data;
}
},
Observer. onerror,
() =>
{
Observer. onnext (lastline );
Observer. oncompleted ();
});
});
}
Of course, after C #5.0, with the support of the native syntax sugar of the compiler, implementing this extension is simpler and more intuitive, but reactive extensions is the foundation of Asynchronization, in addition, in some advanced applications, syntax Sugar cannot replace it. It is necessary to familiarize yourself with this framework.
At present, I am still familiar with things, but I still don't know much about it. I will write an article to introduce it later. If you are interested in this database, you can visit the following links in the repository:
Reactive extensions for. Net (RX)
RX: curing your asynchronous programming blues
Introducing the reactive framework