gpt4 book ai didi

c# - DownloadText() 和 DownloadTextAsync() 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 05:44:00 47 4
gpt4 key购买 nike

在我的代码中,我正在获取容器中 blob 的引用,并对其调用 DownloadText() 方法,但出现错误 找不到接受“CloudBlockBlob”类型的第一个参数的可访问扩展方法“DownloadText”

作为潜在的修复之一,Visual Studio 告诉我使用 DownloadTextAsync() 方法。这两种方法有什么区别?

我使用 new CloudStorageAccount 获取存储帐户,然后使用 storageAccount.CreateCloudBlobClient() 获取 BlobClient。然后在客户端上使用 GetContainerReference() 获取对容器的引用,并在容器引用上使用 GetBlockBlobReference() 获取对 BlockBlob 的引用,然后我调用 blockBlob.DownloadText( ) 向我显示错误 'CloudBlockBlob' 不包含 'DownloadText' 的定义,并且找不到接受类型为 'CloudBlockBlob' 的第一个参数的可访问扩展方法 'DownloadText' (您是否缺少using 指令还是程序集引用?) 并展示如何使用 DownloadTextAsync() 作为潜在的修复方法。

最佳答案

在.net core项目中,如果您使用WindowsAzure.Storage nuget 包中,只有像 DownloadTextAsync 这样的异步方法,没有像 DownloadText 这样的同步方法。

但是新包Microsoft.Azure.Storage.Blob支持同步和异步方法,例如 DownloadTextAsyncDownloadText

这取决于您选择同步或异步方法。

如果文件很大,下载时间较长,并且下载过程中还有其他事情要做,可以选择异步方式。

示例异步代码如下:

class Program
{
static void Main(string[] args)
{
//your other code
CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

Console.WriteLine("in main thread: start download 111");

//assume the download would take 10 minutes.
Task<string> s = myblob.DownloadTextAsync();

//The message will print out immediately even if the download is in progress.
Console.WriteLine("in main thread 222!");

//use this code to check if the download complete or not
while (!s.IsCompleted)
{
Console.WriteLine("not completed");
System.Threading.Thread.Sleep(2000);
}

Console.WriteLine("the string length in MB: "+s.Result.Length/1024/1024);

Console.ReadLine();
}


}

当运行上面的代码时,你可以看到消息 in main thread 222! 立即打印出来,即使下载正在进行中。这意味着您可以在下载过程中执行其他操作(某些其他操作)。他们不会互相阻止。

如果您使用同步方法,如下面的代码:

        static void Main(string[] args)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxx");

var blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference("f22");
CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

Console.WriteLine("in main thread: start download 111");

string s = myblob.DownloadText();

//if the download takes 10 minutes, then the following message will be printed out after 10 minutes.
Console.WriteLine("in main thread 222!");

Console.ReadLine();
}

如果文件很大,需要10分钟才能完成下载。运行代码时,消息in main thread 222!将被阻塞10分钟(下载完成后),然后打印出来。

关于c# - DownloadText() 和 DownloadTextAsync() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56371783/

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