当我们遇到需要异步的 async的方法,再调用的时候就需要 await或者 .result/ .getwaiter().getresult() 这两个的区别在于,当遇到await会把线程挂起,开启别的线程继续后面的操作。但是遇到 .result会一直等在这里,不会开新的线程。很容易造成线程阻塞。 如果有两处使用 .result 还会导致互相等待 造成线程死锁
使用lazy懒加载 可以包装我们的类 直到需要的时候再使用 await xx.value()
的方法 把他加载出来。
private readonly Lazy<Task<CloudBlobClient>> _userClient;
userClient = new Lazy<Task<CloudBlobClient>>(() => GetCloudBlobClientAsync(true));
// 在需要使用的时候
private async Task<CloudBlobContainer> GetContainerAsync(string containerName)
{
return UserContainerNames.Contains(containerName, StringComparer.OrdinalIgnoreCase)
? (await _userClient.Value).GetContainerReference(containerName)
: (await _sysclient.Value).GetContainerReference(containerName);
}
最后的方法
CloudBlobClient userStorageAccount = Task.Run(() => GetCloudBlobClientAsync(true)).GetAwaiter().GetResult();
CloudBlobClient systemStorage = Task.Run(() => GetCloudBlobClientAsync(false)).GetAwaiter().GetResult();