在我的代码中,我正在容器中获取blob的引用,并在其上调用DownloadText()
方法,但出现错误
no accessible extension method 'DownloadText' accepting a first argument of type 'CloudBlockBlob' could be found
作为一种潜在的解决方法,Visual Studio告诉我使用DownloadTextAsync()
方法。两种方法有什么区别?
我要使用new CloudStorageAccount
获取存储帐户,然后使用storageAccount.CreateCloudBlobClient()
获取BlobClient。然后在客户端上使用GetContainerReference()
获取对容器的引用,并在容器引用上使用GetBlockBlobReference()
对BlockBlob的引用,然后调用blockBlob.DownloadText()
,向我显示错误'CloudBlockBlob' does not contain a definition for 'DownloadText' and no accessible extension method 'DownloadText' accepting a first argument of type 'CloudBlockBlob' could be found (are you missing a using directive or an assembly reference?)
,并告诉我使用DownloadTextAsync()
作为潜在的解决方法。
答案 0 :(得分:2)
在.net核心项目中,如果您使用的是WindowsAzure.Storage nuget包,则只有DownloadTextAsync
之类的异步方法,而没有DownloadText
之类的同步方法。
但是新软件包Microsoft.Azure.Storage.Blob确实支持同步和异步方法,例如DownloadTextAsync
和DownloadText
。
取决于您选择同步还是异步方法。
如果文件很大,并且下载时间很长,并且在下载过程中还有其他事情要做,则可以选择异步方法。
示例异步代码如下:
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分钟(下载完成后),然后打印出来。