Asp.net (read/write lock)

Source: Internet
Author: User

Most problems are as follows:

1: write some content to a file and report an exception when reading the file content in another process, thread, or subsequent operations.System. IO. IOException: the file "XXX" is being used by another process, so this process cannot access this file.

2: After some operations are performed on a file (read/write), The append still reportsSystem. IO. IOException: the file "XXX" is being used by another process, so this process cannot access this file.Problem 1 is similar.

3: after some operations are performed on an object, if you want to delete the object, the system still reportsSystem. IO. IOException: the file "XXX" is being used by another process, so this process cannot access this file.

When you see this, experienced students should say that the resources are not released, but there are also the following possibilities. We perform operations on files very frequently. Therefore, we write specific operation classes/components to maintain operations between files. We know that the operation ends at a specific time, such as logs, as the program starts, it starts to write logs until the program is closed. However, we also need to provide a special operation (read, write, and delete) to operate files. For example, we need to provide a log viewer to view the current log or all logs, the above problems are inevitable.
Copy codeThe Code is as follows:
Static void WriteFile (FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
{
Console. WriteLine ("please input your content .");
Var content = Console. ReadLine ();
FileStream fs = new FileStream (FILEPATH, fileMode, fileAccess, fileShare );
Var buffer = Encoding. Default. GetBytes (content );
Fs. Write (buffer, 0, buffer. Length );
Fs. Flush ();
}

First, I declare a file Writing Method and call it to write the content I entered into the specified file.
Copy codeThe Code is as follows:
WriteFile (FileMode. Create, FileAccess. Write, FileShare. Read );
Console. ReadKey ();

However, after the file write operation, I did not release the file stream resources. Therefore, the file will be locked. I tried to delete it in windows.

Obviously, I cannot delete this file. Next, I try to read it.
Copy codeThe Code is as follows:
Static void ReadFile (FileAccess fileAccess, FileShare fileShare)
{
FileStream fs = new FileStream (FILEPATH, FileMode. Open, fileAccess, fileShare );
Var buffer = new byte [fs. Length];
Fs. Position = 0;
Fs. Read (buffer, 0, buffer. Length );
Console. WriteLine (Encoding. Default. GetString (buffer ));
}

I implemented a method for reading files and called it.
Copy codeThe Code is as follows:
WriteFile (FileMode. Create, FileAccess. Write, FileShare. Read );
ReadFile (FileAccess. Read, FileShare. Read );

Everything is simple. The access mode is read-only, so it should not conflict with the above write lock!

However, the result is not what we expected. Why does it prompt that access is unavailable? In retrospect, I opened the file with a windows notepad and did not prompt that the file was locked, and I could indeed access it, so why can't I access it in a program? Perhaps we should focus on the three enumeration types: FileMode, FileAccess, and FileShare, which may be the ghost of them.
FileMode
The explanation on MSDN is to specify the way the operating system opens the file. I don't think I need to explain this. We usually use more. The MSDN table also elaborates the functions of each enumeration value, so I will not explain it.

FileAccess
Defines the constant used for file read, write, or read/write access permissions.

This enumeration is also used a lot, and the description is easy to understand. I cannot explain it again. ^_^!

FileShare
I believe that this enumeration type will be unfamiliar to everyone, and even some people have never seen it before (I am ashamed that it was not long before I knew it). It is a stranger, but its force cannot be underestimated, only. net helped us encapsulate it well, so that we once thought it was not an important role. Okay, go to the topic!

Contains constants used to control the access types that other FileStream objects can have for the same file. What does this sentence mean? To tell the truth, I still find it difficult to read a sentence. I believe many of you may find it confusing. It doesn't matter. Let's skip it first!


Looking at its member description, it is very similar to FileAccess, so let's try to unveil its temporarily mysterious veil!
FileShare. Read
Literally, we can understand that after opening a file (the resource is not released), we can read the file in read-only mode without throwing an exception that the file cannot be accessed. Using the method just implemented, you can easily complete this experiment:

Copy codeThe Code is as follows:
WriteFile (FileMode. Create, FileAccess. Write, FileShare. Read );
ReadFile (FileAccess. Read, FileShare. Read );

What is this? Aren't all set to read? You can only set read-only sharing when reading files. Let's try again:
Copy codeThe Code is as follows:
ReadFile (FileAccess. Read, FileShare. Read );
ReadFile (FileAccess. Read, FileShare. Read );

This is indeed the first time the resource has not been released, so we can try again to write the file after setting the read-only share:
Copy codeThe Code is as follows:
ReadFile (FileAccess. Read, FileShare. Read );
WriteFile (FileMode. Create, FileAccess. Write, FileShare. Read );

First, I read the content of the file correctly, but I reported an error when I tried to write some content. Then, based on the above experiment, we can know that this read-only share is only inContinuous File ReadingValid only!
FileShare. Write
In combination with the Read experience, the literal meaning should be understood as that the file can be written only when the sharing mode is set to Write. Otherwise, an exception will be thrown. When you set Write, the omnipotent Window notepad cannot open the file.

FileShare. ReadWrite
With the above experience, we can literally understand that this ReadWrite must combine the features of Read and Write. So what is its use? As we know above, the Read share setting in the reading file can continue to Read but cannot Write, and the Write share setting can continue to Write but not Read the file while writing, but what should we do when we set the write share and want to read the file? Can only resources be released first and then reloaded? No. ReadWrite is generated for this purpose.
Copy codeThe Code is as follows:
WriteFile (FileMode. Create, FileAccess. Write, FileShare. Read );
ReadFile (FileAccess. Read, FileShare. ReadWrite );

However, when writing a file, you are not allowed to set the share to Write. Otherwise, reading the file using ReadWrite is invalid (an exception is reported), but all are set to ReadWrite. This can solve a lot of daily development troubles.
FileShare. None/FileShare. Delete
With the above experience, I believe you can easily understand the two. None means that subsequent operations are not allowed, and Delete means that you are allowed to perform subsequent deletion operations.

Contents in the black box
For file operations, we usually use the following types of operations:

Copy codeThe Code is as follows:
File. AppendAllText ("......");
File. AppendAllLines (...);
File. AppendText (...);
FileStream fs = new FileStream (path, FileAccess. Write );
Fs. Write (....);

In fact, they also initialize FileMode/FileAccess/FileShare internally. For example, the static method of File will generate a Stream instance, and the private method is called.

Conclusion
Now, we understand that/FileShare is the "access permission" for controlling the file stream. Of course, this is only an entry-level file operation. I made my own notes and hoped to help you, many predecessors have already written articles on file read/write locks in the advanced text garden. If you are interested, you can search and view them !!
Author: Kong Yiyun

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.