我写了一个异步,但是并没有出现预期的效果,请高人们帮我看看为什么 class Program
{
static void Main(string[] args)
{
AsyncRead ar = new AsyncRead();
for (int i = 0; i < 200; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
class AsyncRead
{
byte[] bydata;
char[] chardata;
public AsyncRead()
{
bydata = new byte[100];
chardata = new char[100];
FileStream afile = new FileStream("../../Program.cs", FileMode.Open);
System.AsyncCallback cb = new AsyncCallback(this.HeadelRead);
System.IAsyncResult iar = afile.BeginRead(bydata, 0, 100, cb, "Call Back"); }
private void HeadelRead(IAsyncResult ar)
{
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(bydata, 0, 100, chardata, 0);
Console.WriteLine("value of statue is :{0}", ar.AsyncState);
Console.WriteLine(chardata);
}
}预期效果是:一边输出0~199,一边读取并输出文件中的数据,
但是这段代码的结果却是:先输出了文件中的数据,才输出0~199
{
static void Main(string[] args)
{
AsyncRead ar = new AsyncRead();
for (int i = 0; i < 200; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
class AsyncRead
{
byte[] bydata;
char[] chardata;
public AsyncRead()
{
bydata = new byte[100];
chardata = new char[100];
FileStream afile = new FileStream("../../Program.cs", FileMode.Open);
System.AsyncCallback cb = new AsyncCallback(this.HeadelRead);
System.IAsyncResult iar = afile.BeginRead(bydata, 0, 100, cb, "Call Back"); }
private void HeadelRead(IAsyncResult ar)
{
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(bydata, 0, 100, chardata, 0);
Console.WriteLine("value of statue is :{0}", ar.AsyncState);
Console.WriteLine(chardata);
}
}预期效果是:一边输出0~199,一边读取并输出文件中的数据,
但是这段代码的结果却是:先输出了文件中的数据,才输出0~199
{
Thread.Sleep(100);//或Application.DoEvents();
Console.WriteLine(i);
}
但是在下面的例子中,又不行了啊。。 byte[] bydata = new byte[700];
char[] chardata = new char[700];
FileStream afile = new FileStream("../../Program.cs", FileMode.Open);
afile.Seek(0, SeekOrigin.Begin);
IAsyncResult result = afile.BeginRead(bydata, 0,700, null, null);
while (!result.IsCompleted)
{
System.Windows.Forms.Application.DoEvents();//这句是加的
Console.WriteLine("reading ...");
}
afile.EndRead(result);
Decoder d = Encoding.ASCII.GetDecoder();
d.GetChars(bydata, 0, bydata.Length, chardata, 0);
Console.WriteLine(chardata);
Console.Read();至于这我写的异步没有出现预期效果,可以告知下原因吗,谢谢了啊