Reading files in a single thread

Source: Internet
Author: User
Code

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;
Using System. IO;

Namespace ExToDB. FileTransfer
{
Public class FileComsumer
{
Private string fileName;
Private Stream streamOuput = null;
Private int bufferSize = 1024;

Private Thread fileThread = null;
Private volatile bool isStop;

Public event ReturnEndEvent OnReadEnd;

Public FileComsumer (string fileName)
{
IsStop = false;
This. fileName = fileName;
}

/// <Summary>
/// Obtain the read Stream
/// </Summary>
Public Stream StreamOuput
{
Get {return streamOuput ;}
}

Public void Start ()
{
FileThread = new Thread (new ThreadStart (TheadReadFile ));
FileThread. Start ();
}

Public void Stop ()
{
IsStop = true;
If (fileThread! = Null & fileThread. ThreadState = System. Threading. ThreadState. Running)
FileThread. Abort ();
FileThread = null;
}

Private byte [] buffer = null;

/// <Summary>
/// Obtain the read data
/// </Summary>
Public byte [] Buffer
{
Get {return buffer ;}
}

Private void TheadReadFile ()
{
StreamOuput = new FileStream (fileName, FileMode. Open, FileAccess. Read, FileShare. Read, bufferSize, true );
Int numBytesToRead = (int) streamOuput. Length;
Int numBytesRead = 0;
Buffer = new byte [streamOuput. Length];
While (numBytesToRead> 0 &&! IsStop)
{
// Read may return anything from 0 to numBytesToRead.
Int n = streamOuput. Read (buffer, numBytesRead, numBytesToRead );
// The end of the file is reached.
If (n = 0)
{
OnOnReadEnd ();
Break;
}
NumBytesRead + = n;
NumBytesToRead-= n;
// File Reading is complete, triggering the event
If (numBytesToRead = 0)
OnOnReadEnd ();
}
StreamOuput. Close ();
}

Private void OnOnReadEnd ()
{
If (this. OnReadEnd! = Null)
OnReadEnd (this, new ReturnEndReadEventargs (true ));
}
}
}

 

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.