Visual Studio .NET 2002Visual C++ 7.1Visual C++ 7.0.NET 1.0Windows 2003Windows 2000Windows XP中级开发Visual StudioJavascriptWindowsC++.NETVisual BasicASP.NETC#
长读写流上的事件通知






3.23/5 (11投票s)
2003年8月12日

44678

1065
一篇关于对大型流操作进行事件通知的文章...
引言
有时在编程过程中,会有些方法接收一个流,然后在该流上执行某些函数。通常,如果流比较大,则该方法可能需要很长时间才能返回(例如,通过网络对 2 GB 文件进行 SHA1 计算需要大约 20 分钟)。有些应用程序只想在发生了一些活动时收到通知,并希望了解活动量。收到即将读取或已读取的字节块的通知可以解决此问题。因此,EventStream
读取器尝试解决此问题。有关更多信息,请参阅示例。
使用代码
以下是使用此类的示例,用于在可能需要很长时间的 SHA1 计算期间收到通知。
class ExampleNotifyClass
{
public int timesNotified = 0 ;
public void SectionWasRead( byte[] buff, int index, int count )
{
Console.WriteLine("Section read: {0}", count ) ;
timesNotified++ ;
}
///
/// Main
///
public static void Main() {
// Create the sample data to read
MemoryStream mem = new MemoryStream() ;
StreamWriter writer = new StreamWriter(mem, Encoding.UTF8) ;
// Populate the stream
for( int i = 0 ; i < 16 * 777 ; i++ )
{
writer.WriteLine( "{0}", i % 10 ) ;
}
// Reset the pointer in the stream
mem.Seek( 0, SeekOrigin.Begin ) ;
// Create a sample class
ExampleNotifyClass toNotify = new ExampleNotifyClass();
EventStream toRead = new EventStream( mem ) ;
toRead.AfterBlockRead += new
EventStream.AfterBlockHandler(toNotify.SectionWasRead ) ;
toRead.BlockEventSize = 8192 ;
// Get notified for every 8192 bytes read
SHA1 sha = new SHA1Managed() ;
// Actual work is done here
byte[] hash = sha.ComputeHash( toRead ) ;
Console.WriteLine( "Our class was notified {0} times.",
toNotify.timesNotified ) ;
}
}