[英]Initializing async rest api's instead of doing it in a constructor -c# .Net
我必須通過 rest 調用獲取一些數據並緩存它們,以便可以在我正在工作的 SDK 中使用它只是想確定這是否是正確的方法,或者想知道是否可以以更好的方式完成
public class Library {
private bool isInitialized;
public Library(...dependencies) {}
public async Task InitializeAsync() {
if (!isInitialized) {
var data1 = await "api call";
var data2 = await "api call2";
isInitialized = true
//cache them
}
}
}
您應該使用具有線程安全設置的Lazy<>
。
公共 class 庫 {
private Lazy<somedata> _someData;
public Library(...dependencies)
{
_someData = new Lazy<somedata>(() => initialise and store data);
}
public void DoSomething()
{
var somedata = _someData.Value; <--- this will initialise the first time it's used
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.