您能否提供有关如何在异步模式下逐行读取文件的示例代码或链接?
我必须一次读取一行文件(或至少 30 个字节的数据)并将其显示在文本框中,例如 textBox1。为此,我必须使用异步读取模式。我怎样才能做到这一点?
我正在使用 C# Windows 应用程序 IDE - Visual Studio 2008
您可以使用BeginRead方法。例如,您可以定义一个状态对象,该对象将包含有关正在读取的流和内容的信息:
public class State
{
public Stream Stream { get; set; }
public byte[] Buffer { get; set; }
}
然后开始以 30 字节的块异步读取文件:
var stream = File.OpenRead("SomeFile.txt");
var state = new State
{
Stream = stream,
Buffer = new byte[30]
};
stream.BeginRead(state.Buffer, 0, state.Buffer.Length, EndRead, state);
该EndRead
方法可以这样定义:
private void EndRead(IAsyncResult ar)
{
var state = ar.AsyncState as State;
var bytesRead = state.Stream.EndRead(ar);
if (bytesRead > 0)
{
string value = Encoding.UTF8.GetString(state.Buffer, 0, bytesRead);
// TODO: do something with the value being read
// Warning: if this is a desktop application such as WinForms
// and you need to update some control on the GUI make sure that
// you marshal the call on the main UI thread, because this EndRead
// method will be invoked on a thread drawn from the thread pool.
// In WinForms you need to use Control.Invoke or Control.BeginInvoke
// method to marshal the call on the UI thread.
state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, EndRead, state);
}
else
{
// finished reading => dispose the FileStream
state.Stream.Dispose();
}
}
我猜你正在尝试从另一个线程读取文件。看看这是否对你有帮助,因为很难理解你到底想要做什么。
此外,正如@Darin 在评论中提到的,您应该阅读有关FileStream.BeginRead方法的信息。请注意,如果您使用的是 .Net 4.5,则可以使用ReadAsync方法。