我決定寫一個函數來計算文件中的字節數。差異調用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
你的問題是什麼?等待關鍵字將釋放當前線程返回給調用者,然後在方法完成時再次拿起。無需等待您不會釋放當前線程並將同步執行 –