When working with files, the code we want to write is robust. If a long-running file handler does not perform a robust operation on the file, there are some problems.
such as an HTTP server, it is mainly to open the file and read the content, sent to the requestor. If there is a problem with the network connection, which causes the file being transferred to not be closed, we can only restart the HTTP server if we want to modify the contents of the file.
In order to write robust file handling code, we usually use the try-catch-finally statement block:
1FileStream file = null;
2try
3{
4 file = new FileStream (path, mode, access);
5//do something
6}
7catch (IOException e)
8{
9 throw e;
11finally
12{
if (file!= null)
{
file. Close ();
17}
Wouldn't it be annoying if your code is full of code that's in this pattern? If you read the contents of a file, the code that might really be useful is just a few lines of code. For robustness, we have to write 10 lines of code to handle exceptions and close files.
Do you think of the encapsulation of these patterns of code? Not bad! In order to write less code, encapsulation is a good thing, and we can focus on this pattern of code. As far as thinking is concerned, we use the changed content as the parameter of the method. We use proxies for code that handles changes while encapsulating this operation.
It is not difficult to encapsulate this mode of operation.
First we need a proxy that contains a FileStream type of argument:
delegate void Processfilestreamcallback (FileStream file);
Although the name of this agent is very long, we can use the anonymous function to reduce the number of words.