c# - What is the best way to wait to next line from a fast-growing file? -
i need read fast-growing test file, , process new lines asap. file can updated several time per millisecond.
if introduce sleep @ "problem" line of code (as below), works nicely introduce 1 millisecond delay.
if comment out "problem" line, no delay cpu usage gets toward 70%.
is there better way resolve this?
public void updatepricesfromsfile() { using (txtfilereader = new streamreader(file.open(filename, filemode.open, fileaccess.read, fileshare.readwrite))) { txtfilereader.basestream.seek(0, seekorigin.end); while (true) { while ((line = txtfilereader.readline()) == null) { system.threading.thread.sleep(1); //problem } //process line } } }
extending comment code sample :
public abstract class filewatcher { // last known position of stream int m_laststreamposition; // flag check if file in read state volatile bool m_isreading; // info file fileinfo m_fileinfo; // file system watcher filesystemwatcher m_watcher; // standard ctor used watch specific file public filewatcher(string filepath) { // create new instance of filesystem using path of file m_fileinfo = new fileinfo(filepath); // if ( !m_fileinfo.exists ) throw new invalidargumentexception("filepath"); // start watcher based on fileinfo m_watcher = new filesystemwatcher(m_fileinfo.directoryname, m_fileinfo.extension); m_watcher.enableraisingevents = true; m_watcher.changed += whenfilechanged; // reset stream position , read file initialy m_laststreamposition = 0; readfile(); } // event fired when file changed // !! note fire whenever create file in same // directory desired file , same extension // , change/modify file void whenfilechanged(object source, filesystemeventargs e) { // based on note comment, check if that's our desired file if ( e.fullpath != m_fileinfo.fullname ) return; // refresh informations file m_fileinfo.refresh(); // check if added file, // in case removed (?) reset laststreamposition (?) if ( m_fileinfo.length <= m_laststreamposition ) m_laststreamposition = 0; // read file readfile(); } void readfile() { if ( m_isreading ) return; m_isreading = true; using ( streamreader reader = m_fileinfo.opentext() ) { reader.basestream.position = m_laststreamposition; string line = string.empty; while ( ( line = reader.readline() ) != null ) { processline(line); } m_laststreamposition = reader.basestream.position; } m_isreading = false; } protected abstract void processline(string line); }
sample usage :
public class mefilewatcher : filewatcher { public mefilewatcher(string filepath) : base(filepath) { } protected override void processline(string line) { console.writeline ("new line added -> {0}", line); } } mefilewatcher mefilewatcher = new mefilewatcher("d:\\testdata\\mefile.txt");
Comments
Post a Comment