gpt4 book ai didi

c# - 从 C# 将文件上传到 Azure 文件时如何更改最大并发值?

转载 作者:行者123 更新时间:2023-12-02 07:22:01 29 4
gpt4 key购买 nike

我正在尝试将文件(约 250Mb 大小)上传到 Azure 文件共享(不是 blob 存储),多次重试后上传失败,并抛出异常,提示请求在 6 次重试后失败。我在将文件上传到 azure blob 存储时遇到了完全相同的问题,我发现我需要减少 BlobUploadOptions 上的并发线程数,因为我的网络速度无法处理大量并行上传线程。现在,要上传到 Azure 文件共享,我无法找到可以设置上传最大并发数的属性。关于如何设置它有什么想法吗?或者有其他替代解决方案吗?附:我正在使用 .NET Azure SDK v12

我正在使用的代码:

                string shareName = "test-share";
string dirName = "sample-dir";
string fileName = Path.GetFileName(localFilePath);

ShareClient share = new ShareClient(ConnectionString, shareName);
await share.CreateAsync();

ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
await directory.CreateAsync();

ShareFileClient fileClient = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
await fileClient.CreateAsync(stream.Length);
await fileClient.UploadRangeAsync(
new HttpRange(0, stream.Length),
stream);
}

我在上传到 blob 存储时解决了这个问题,如下所示:

                     BlobUploadOptions uploadOptions = new BlobUploadOptions() {
TransferOptions = new Azure.Storage.StorageTransferOptions() {
MaximumConcurrency = 2,
InitialTransferSize = 100 * 1024 * 1024
}
};

using (FileStream uploadFileStream = File.OpenRead(filePath))
{
await blobClient.UploadAsync(uploadFileStream, uploadOptions);
uploadFileStream.Close();
}

最佳答案

查看.NET Azure SDK v12的源代码后,发现文件共享没有这样的设置。

作为解决方法,您可以先对文件进行分块,然后逐个上传这些分块文件。在这种情况下,不存在并发。示例代码如下:

        //other code            

ShareFileClient fileClient = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
await fileClient.CreateAsync(stream.Length);

int blockSize = 1 * 1024 * 1024;
long offset = 0;//Define http range offset
BinaryReader reader = new BinaryReader(stream);
while (true)
{
byte[] buffer = reader.ReadBytes(blockSize);
if (buffer.Length == 0)
break;

MemoryStream uploadChunk = new MemoryStream();
uploadChunk.Write(buffer, 0, buffer.Length);
uploadChunk.Position = 0;

HttpRange httpRange = new HttpRange(offset, buffer.Length);
var resp = await fileClient.UploadRangeAsync(httpRange, uploadChunk);
offset += buffer.Length;//Shift the offset by number of bytes already written
}

reader.Close();
}

顺便说一句,有一个 Azure Storage Data Movement Library ,如果你选择使用它来上传文件,你就有机会控制并发。

关于c# - 从 C# 将文件上传到 Azure 文件时如何更改最大并发值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64029746/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com