使用异步的困惑?

学习一下异步的使用,找了一个例子,一边读取文件,一边显示数字,
首先建立了WinForm程序,测试结果,读取的数据显示的不正确;除此以外,同下面的Console有相同的问题;
然后按照示例建立Console程序,读取的数据倒是没有问题了,
但是没有异步操作,不论读取的文件多大,都是先读完,然后再显示数字,奇怪啊?

问题原因还没有找到,幸好,我么还有多线程。


Console的代码如下:

using System;
using System.IO;
using System.Text;
using System.Threading;
namespace TestAsync
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>

    class Class1
    
{
        
private Stream inputStream;
        
// delegated method
        private AsyncCallback myCallBack;
        
// buffer to hold the read data
        private byte[] buffer;
        
// the size of the buffer
        const int BufferSize = 256;
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main(string[] args)
        
{
            
//
            
// TODO: 在此处添加代码以启动应用程序
            
//
            
// create an instance of AsynchIOTester
            
// which invokes the constructor
            Class1 theApp =    new Class1();
            
// call the instance method
            theApp.Run( );
        }

        
public Class1()
        
{
            
// open the input stream
            inputStream =
                File.OpenRead(
                
@"C:\test.txt");
            
// allocate a buffer
            buffer = new byte[BufferSize];
            
// assign the call back
            myCallBack =
                
new AsyncCallback(this.OnCompletedRead);
        }

        
void Run( )
        
{
            inputStream.BeginRead(
                buffer, 
// holds the results
                0// offset
                buffer.Length, // (BufferSize)
                myCallBack, // call back delegate
                null); // local state object
            
// do some work while data is read
            for (long i = 0; i < 1000; i++)
            
{
                
if (i%10 == 0)
                
{
                    Console.WriteLine(
"i: {0}", i);
                }

            }

        }

        
// call back method
        void OnCompletedRead(IAsyncResult asyncResult)
        
{
            
int bytesRead =
                inputStream.EndRead(asyncResult);
            
// if we got bytes, make them a string
            
// and display them, then start up again.
            
// Otherwise, we're done.
            if (bytesRead > 0)
            
{
                String s 
=
                    Encoding.ASCII.GetString(buffer, 
0, bytesRead);
                Console.WriteLine(s);
                inputStream.BeginRead(
                    buffer, 
0, buffer.Length, myCallBack, null);
            }

        }

    }

}

posted on 2006-10-31 10:46  Pierce  阅读(787)  评论(0)    收藏  举报

导航