c# – C # – Freeing a file

Question:

There are BinaryReader and BinaryWriter which write and read at the same time. There is a progressBar. When I close the application while working, I get an Exception in progressBar and using the delegate I do Close () & Dispose () BinaryReader, BinaryWriter and FileStream, which is used in BinaryReader. Nevertheless, the file is not released for some reason.

streamRead – FileStream; reader – BinaryReader;

using (streamRead = new FileStream(filePath, FileMode.Open))
        {
            reader = new BinaryReader(streamRead);

writer – BinaryWriter

 using (writer = new BinaryWriter(File.Open(this.txbxArchivePath.Text + @"\" + this.txbxArchiveName.Text + ".Haffman", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))){ }

the method that I call using the delegate:

private void DisposeAll()
    {
        this.reader.Close();
        this.writer.Close();
        streamRead.Close();

        this.reader.Dispose();
        this.writer.Dispose();
        streamRead.Dispose();

        this.Dispose();
    }

Answer:

On MSDN they write :

"Do not interrupt the thread that is performing the read operation. Although the application may appear to execute successfully after the thread is not blocked, interruptions can degrade the performance and reliability of the application." most likely this is what was meant

Surely, it was meant that the execution of the Close() & Dispose() methods may not be executed correctly.

Try this example:

 class MyReader
{
    bool _breakReader = false;

    public void Close()
    {
        _breakReader = true;
    }

    public byte[] Read(string file)
    {
        byte[] bytes;
        try
        {

            using (FileStream fsSource = new FileStream(file,
                FileMode.Open, FileAccess.Read))
            {

                bytes = new byte[fsSource.Length];
                //Здесь можно указать нужный буфер 
                int numBytesToRead = 1024*1024; //1 МБ
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    int n = fsSource.Read(bytes, 
                        numBytesRead, numBytesToRead);
                    // Здесь будет прерывание считывания
                    if (n == 0 || _breakReader )
                        break;

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
            }
        }
        catch (FileNotFoundException ioEx)
        {
            Console.WriteLine(ioEx.Message);
        }
        return bytes;
    }
}

As a result, it turns out that we read the file one megabyte at a time, if during reading the flag changed to true , then we interrupt the reading cycle and correctly close the FileStream

Scroll to Top
AllEscort