gpt4 book ai didi

c# - Package.Current.InstalledLocation.GetFileAsync 和 StorageFile.CopyAsync 未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:12 31 4
gpt4 key购买 nike

我需要使用 SQlite 数据库“播种”我的应用程序。我使用了@Kasper 在帖子 How to deploy a database file with a Xamarin.form app? 中建议的代码.

我的 UWP 代码如下所示。

public async Task<String> GetDBPathAndCreateIfNotExists()
{
String filename = "birdsnbflys.db3";
bool isExisting = false;
try
{
StorageFile storage = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
isExisting = true;
}
catch (Exception)
{
isExisting = false;
}
if (!isExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync(filename);
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, filename, NameCollisionOption.ReplaceExisting);

}
return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
}

当我在“本地机器”上运行它时,它“挂起/从不返回”

StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync(filename);

如果我查看 Package.Current.InstalledLocation 文件夹,数据库文件就在那里。

当我在其中一个设备模拟器上运行它时,它“挂起/从不返回”

await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, filename, NameCollisionOption.ReplaceExisting);

在这种情况下,如果我退出应用程序然后重新启动它,文件现在位于 ApplicationData.Current.LocalFolder 中,因此应用程序可以运行。

考虑到我的应用程序的需求,我很乐意使用同步方式来执行此操作,但看起来 Microsoft 除了异步之外没有提供任何东西。

关于如何让它按预期工作有什么想法或建议吗?

谢谢,戴夫

最佳答案

首先,我建议您使用 TryGetItemAsync,而不是使用 GetFileAsync。这样,您就可以避免 try-catch block 。
此外,您应该在您的案例中使用 ConfigureAwait(false) 。您不需要该方法在同一线程上返回。最终,您的问题是由死锁引起的。

// The caller of this method may use ConfigureAwait(false) as well,
// depending on the call-site and result-usage.
public async Task<String> GetDBPathAndCreateIfNotExists()
{
String filename = "birdsnbflys.db3";

// Check if file exists
var file = await ApplicationData.Current.LocalFolder.TryGetItemAsync(filename).ConfigureAwait(false);
var fileExists = file != null;

// If the file doesn't exist, copy it without blocking the task
if (!fileExists)
{
var databaseFile = await Package.Current.InstalledLocation
.GetFileAsync(filename)
.ConfigureAwait(false);
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder,
filename,
NameCollisionOption.ReplaceExisting)
.ConfigureAwait(false);
}

return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
}

关于c# - Package.Current.InstalledLocation.GetFileAsync 和 StorageFile.CopyAsync 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042444/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com