-4

非同期モードでファイルを1行ずつ読み取る方法のサンプルコードまたはリンクを提供できますか?

ファイルを一度に1行(または少なくとも30バイトのデータ)読み取って、テキストボックス(textBox1など)に表示する必要があります。これを行うには、非同期読み取りモードを使用する必要があります。どうすればこれを達成できますか?

私はC#WindowsアプリケーションIDEを使用しています-Visual Studio 2008

4

2 に答える 2

3

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();
    }
}
于 2012-10-15T10:32:54.867 に答える
0

別のスレッドからファイルを読み取ろうとしていると思います。正確に何をしようとしているのかを理解するのは難しいので、これが役立つかどうかを確認してください..

また、@Darin がコメントで述べたように、FileStream.BeginReadメソッドについて読む必要があります。.Net 4.5 を使用している場合は、ReadAsyncメソッドを使用できることに注意してください。

于 2012-10-15T09:47:19.283 に答える