我决定写一个函数来计算文件中的字节数。差异调用FileStream.ReadAsync有/没有等待
“正常”和异步。
所以我写了以下功能:
功能1个
public static async Task<int[]> ByteFrequencyCountAsync(string fname)
{
// freqs
int[] counted = new int[256];
// buf len
int blen = FileAnalisys.ChooseBuffLenght(fname);
// buf
byte[] buf = new byte[blen];
int bytesread;
using (FileStream fs = new FileStream
(
fname,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
blen,
FileOptions.Asynchronous
))
{
while ((bytesread = await fs.ReadAsync(buf, 0, blen)) != 0)
{
foreach (byte b in buf)
counted[b]++;
}
}
return counted;
}
功能2
public static int[] ByteFrequencyCount(string fname)
{
Task<int[]> bytecount = Task.Run<int[]>(() =>
{
// freqs
int[] counted = new int[256];
// buf len
int blen = FileAnalisys.ChooseBuffLenght(fname);
// buf
byte[] buf = new byte[blen];
int bytesread;
using (FileStream fs = new FileStream
(
fname,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
blen,
FileOptions.Asynchronous
))
{
while ((bytesread = fs.ReadAsync(buf, 0, blen).Result) != 0)
{
foreach (byte b in buf)
counted[b]++;
}
}
return counted;
});
return bytecount.Result;
}
我觉得功能1个执行读取和异步功能2同步进行。
功能1个
while ((bytesread = await fs.ReadAsync(buf, 0, blen)) != 0)
功能2
while ((bytesread = fs.ReadAsync(buf, 0, blen).Result) != 0)
总之。我猜测任务没有等待和未标记为异步执行通过线程池,但同步。所以我可以更改fs.ReadASync fs.Read并没有任何反应。
需要一只手,因为我有点困惑。
EDIT1: 功能2应该是同步,所以我关于它的问题:
代码的工作,但我认为使用FileStream.Asynchronous有没有意义。
我想用fs.ReadASync来代替fs.Read并没有真正的好处。所以它应该被 fs.Read取代。
这是不一样的。只看到返回类型。所以'bytesread = fs.ReadAsync(......)'是不可编译的。 –
你在问什么?我在这里没有看到问题。 – Servy
你的问题是什么?等待关键字将释放当前线程返回给调用者,然后在方法完成时再次拿起。无需等待您不会释放当前线程并将同步执行 –