Xamarin.forms 为什么静态类实例在等待期间将为null?
我已经有了一个部分完成的Xamarin解决方案,它在Android中工作。我正在尝试添加UWP支持(我确实理解这还不是全部)。我在下面的代码中调用State.RestoreSystemIndex()。我在第一行有一个断点,我可以看到CurrentSystem被填充(正如我所期望的)。我一步一步地浏览代码,当Xamarin.forms 为什么静态类实例在等待期间将为null?,xamarin.forms,xamarin.uwp,Xamarin.forms,Xamarin.uwp,我已经有了一个部分完成的Xamarin解决方案,它在Android中工作。我正在尝试添加UWP支持(我确实理解这还不是全部)。我在下面的代码中调用State.RestoreSystemIndex()。我在第一行有一个断点,我可以看到CurrentSystem被填充(正如我所期望的)。我一步一步地浏览代码,当return wait SecureStorage.GetAsync(key)完成时,CurrentSystem现在为null,当然对它的引用失败了。在等待SecureStorage.GetA
return wait SecureStorage.GetAsync(key)
完成时,CurrentSystem现在为null,当然对它的引用失败了。在等待SecureStorage.GetAsync(key)的过程中,什么会使CurrentSystem变为null
公共类配置
{
public const int SystemIndexUndefined=-1;
public int SystemIndex=SystemIndexUndefined;
/*等等*/
};
公共静态类状态
{
公共静态配置CurrentSystem=新配置();
/*剪断*/
私有静态异步任务OurGetAsync(字符串键)
{
尝试
{
return wait SecureStorage.GetAsync(key);
}
捕获(例外情况除外)
{
Logger.LogMsg($“GetAsync({key})引发的异常{ex}”);
}
返回null;
}
公共静态异步void RestoreSystemIndex()
{
字符串s=等待我们的GetAsync(“系统索引”);
如果(s==null)CurrentSystem.SystemIndex=Configuration.SystemIndexUndefined;//未记录
else CurrentSystem.SystemIndex=转换为32(s);
}
/*等等*/
I将return await拆分为两条语句,字符串s=await GetAsync()和return s。在等待期间,静态值将为null,而不是return。FWIW,调试器显示await GetAsync()耗时1293毫秒。Visual Studio 2019 Community Edition在Windows Pro 64位上运行。已确定它仅在我在VS中运行项目的第二次和后续时间发生。如果我退出VS并重新启动它,则我可以成功运行项目一次。
public class Configuration
{
public const int SystemIndexUndefined = -1;
public int SystemIndex = SystemIndexUndefined;
/* etc. */
};
public static class State
{
public static Configuration CurrentSystem = new Configuration();
/* snip */
private static async Task<string> OurGetAsync(string key)
{
try
{
return await SecureStorage.GetAsync(key);
}
catch (Exception ex)
{
Logger.LogMsg($"Exception {ex} thrown by GetAsync({key})");
}
return null;
}
public static async void RestoreSystemIndex()
{
string s = await OurGetAsync("SystemIndex");
if (s == null) CurrentSystem.SystemIndex = Configuration.SystemIndexUndefined; // Not recorded
else CurrentSystem.SystemIndex = Convert.ToInt32(s);
}
/* etc. */