我目前正在编写自己的杂乱的P2P网络(只是为了好玩),并且正在尝试学习异步。我想调用以下函数,该函数将返回要发送文件的byte []块。然后,main函数将委派该块的传输。函数是否有可能多次返回数据,等待上一个块的传输完成,然后再将下一个块读入内存?我知道我可以编写使用索引跟踪参数多次调用的函数,但是如果可能的话,希望使用异步,因为这似乎是一个完美的用例。
public async Task<byte[]> ChunkData(string str)
{
byte[] tempData = new byte[BUFFER_SIZE]; //Stores one chunk of data
byte[] dataBytes = Encoding.Default.GetBytes(str); //Stores all data TODO: convert to filestream
int extraBytes = 0; //Track any extra bytes after we have exhausted full chunks
int dataChunks = dataBytes.Length / BUFFER_SIZE; //Determine how many chunks are in the file
for (int i = 0; i <= dataChunks; i++) //Loop for all dataChunks and once more for extraBytes
{
if (i == dataChunks) //Last iteration
{
extraBytes = dataBytes.Length - dataChunks * BUFFER_SIZE;
if (extraBytes == 0) break; //Break if no extra bytes
}
int endPoint = dataChunks > 0 ? (BUFFER_SIZE * (i != dataChunks ? (i + 1) : i)) : 0;
int frontPoint = i == 0 ? 0 : (BUFFER_SIZE * i);
tempData = dataBytes[frontPoint..(endPoint + extraBytes)]; //Assign tempData to range
Console.WriteLine(Encoding.Default.GetString(tempData)); //For debugging
}
}