Looked at some blog posts online about saving Stream to a file,Many are incorrect。 (I found several problems: poor performance, abnormal when the stream is too large)
After getting a Stream how to elegantly save this Stream to code
The most elegant method should be through the method of CopyTo or CopyToAsync
here inputStream.Seek(0, SeekOrigin.Begin); Not necessarily, please use this code according to your own needs, such as you only need to copy the stream from the 10th byte, etc
Using the asynchronous approach will take a little longer for this write, but it will give the overall performance better and allow the CPU to handle other tasks
Note that when using CopyToAsync, remember to add await, when executing this code, you will hand over the execution to IO, most IO processing does not require CPU to compute, so that the overall performance can be better
Also, if the iputStream is coming in from outside, then I don't recommend releasing it inside this method, why? I used a good stream and it was killed when I passed in a business
The second method is to control the memory replication cache yourself, which will have an additional memory copy
What this method does is allow you to modify the value of new byte[1024], giving you control over the copied cache
The next are some methods that are not recommended, but they are convenient when writing
The above method will copy the memory twice, and if the input resource length is 1G, it will occupy 2G of resources
Similar to the above is to request a large cache, as shown in the following code
In terms of efficiency and code elegance, they are actually inferior to the CopyTo method, and because of stream. Length as length does not determine the cache, so it is not as good as the second method
Below is a super slow method, one byte by one byte writing is super slow
Transferred from:The hyperlink login is visible. (End)
|