1
這可能是一個愚蠢的問題。但是當我修改Live SDK的一個例子時,出現了一個奇怪的問題。爲什麼我的List在函數調用中分配後爲空?
我在想根本原因是異步函數GetAll()被同步使用。
下面是代碼片段,我把問題作爲註釋。提前致謝!
class SkyeDriveViewModel: INotifyPropertyChanged
{
private List<SkyDriveItem> folderList = null;
public List<SkyDriveItem> FolderList
{
get { return folderList; }
private set
{
if (value != folderList)
{
folderList = value;
NotifyPropertyChanged("FolderList");
}
}
}
private async void GetAll(string desiredPath)
{
FolderList = new List<SkyDriveItem>();
this.liveClient = new LiveConnectClient(SkyDrivePage.Session);
try
{
LiveOperationResult operationResult = await this.liveClient.GetAsync(desiredPath);
dynamic result = operationResult.Result;
dynamic items = result.data;
foreach (dynamic item in items)
{
SkyDriveItem newItem = new SkyDriveItem(item);
if (newItem.IsFolder)
{
FolderList.Add(newItem);
}
}
}
catch (LiveConnectException e)
{
}
//**till here, FolderList was assigned**
}
public void InitList()
{
Debugger.Log();
GetAll(SKYDRIVEINITPATH);
Debugger.LogWhen(eDebugger.LogTiming.Exit);
//**till here, FolderList had zero item**
}
}
+1。如果調用函數*必須*同步,'GatAll'應該返回'Task'並且你可以調用'Wait'結果。 –
@AlexeiLevenkov如果調用者需要它是同步的,那麼該方法可能不應該異步開始... – Servy
@Servy感謝您的答案! – tao