I am currently working on writing my own disorganized P2P network (just for fun) and am trying to learn async. I want to call the following function which will return a byte[] chunk of the file being sent. Then, the main function will delegate the transmission of that chunk. Is it possible to have the function return data multiple times, waiting for the transmission of the previous chunk to finish before reading the next chunk into memory? I know I can write the function to simply be called several times with index-tracking arguments but would like to use async if possible since this seems like a perfect use-case.
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
}
}