在c#中调用并行线程上的异步函数



我有一个三个异步函数,我想同时从多个线程并行调用。到目前为止,我已经尝试了以下方法-

int numOfThreads = 4; 
var taskList = List<Task>(); 
using(fs = new FileStream(inputFilePath, FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite))
{
for(int i=1; i<= numOfThreads ; i++) 
{
taskList.Add(Task.Run( async() => {
byte[] buffer = new byte[length]; // length could be upto a few thousand
await Function1Async(); // Reads from the file into a byte array
long result = await Function2Aync(); // Does some async operation with that byte array data
await Function3Async(result); // Writes the result into the file 
}
}
}
Task.WaitAll(taskList.toArray());  

然而,并不是所有的任务都在执行结束前完成。我在c#中使用线程的经验有限。我在代码中做错了什么?或者我应该采取另一种方法?

编辑-所以我对我的方法做了一些改变。我现在去掉了Function3Async -

for(int i=1;i<=numOfThreads; i++) 
{
using(fs = new FileStream(----))
{
taskList.Add(Task.Run( async() => {
byte[] buffer = new byte[length]; // length could be upto a few thousand
await Function1Async(buffer); // Reads from the file into a byte array
Stream data = new MemoryStream(buffer); 
/** Write the Stream into a file and return 
* the offset at which the write operation was done
*/
long blockStartOffset = await Function2Aync(data); 
Console.WriteLine($"Block written at - {blockStartOffset}");
}
}
}
Task.WaitAll(taskList.toArray());

现在所有线程似乎都完成了,但是Function2Async似乎随机地将一些日文字符写入输出文件。我猜这可能是一些线程问题?下面是Function2Async ->

的实现
public async Task<long> Function2Async(Stream data)
{
long offset = getBlockOffset(); 
using(var outputFs = new FileStream(fileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite))
{
outputFs.Seek(offset, SeekOrigin.Begin);
await data.CopyToAsync(outputFs);     
}
return offset;
}

在你的例子中,你既没有通过fs也没有通过buffer进入Function1Async,但你的评论说它从fs读取到buffer,所以我假设这就是发生的事情。

不能并行地从流中读取。它不支持这种说法。如果您找到一个支持它的,它将非常低效,因为这就是硬盘存储的工作方式。如果是网络驱动器就更糟了。

从流读入缓冲区,首先,然后依次,然后让线程松散并运行逻辑。在内存中已经存在的缓冲区上并行执行。

如果你写的是同一个文件,那么写也会有同样的问题。如果每个缓冲区写一个文件,那很好,否则,按顺序写。

最新更新