an2*_*n22 1 .net c# task async-await maui
在下面的方法中,我只希望result在为结果赋值后对变量进行空检查。我认为现在发生的情况是,有时空检查是在FilePicker.PickAsync()完成之前发生的,因此结果尚未分配值。相反,我只希望在用户选择文件后进行空检查。
private async void PickFileButton_Clicked(object sender, EventArgs e)
{
try
{
Console.WriteLine("checkpoint1");
FileResult result = await FilePicker.PickAsync(new PickOptions
{
FileTypes = new FilePickerFileType(
new Dictionary<DevicePlatform, IEnumerable<string>>
{
{ DevicePlatform.iOS, new[] { "public.item" } },
{ DevicePlatform.Android, new[] { "*/*" } },
{ DevicePlatform.WinUI, new[] { "*/*" } },
{ DevicePlatform.MacCatalyst, new[] { "public.item" } }
})
}); ;
Console.WriteLine("checkpoint2");
if (result.FileName != null)
{
filePath = result.FullPath;
FilePathLabel.Text = filePath;
Console.WriteLine(FilePathLabel.Text);
}
}
catch (Exception ex)
{
// Handle exception if file picker operation fails
Console.WriteLine($"File picking failed: {ex.Message}");
}
}
Run Code Online (Sandbox Code Playgroud)
我仍然不完全确定这就是问题所在。它引起了我的注意,因为它FilePathLabel没有被更新,当我添加断点时,我注意到结果有时为空。此外,此问题仅在您首次运行程序并且用户选择文件时发生。第一次选择他们的文件后,如果他们再试一次,那么一切似乎都有效,但我不明白。
代码正在等待 - 只是:结果是null(由于取消或某些内部故障)。所以:检查一下:
if (result?.FileName is not null)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
(在语义上类似于if (result is not null && result FileName is not null))