在杀死/背景后,何时与context(不可能)与工人使用代码来运行代码?

发布于 2025-01-19 09:16:47 字数 392 浏览 1 评论 0原文

我有一个简单而快速的操作,例如将重要日志插入磁盘数据库中。即使用户关闭应用程序(我们不想丢失日志),也需要保证这一点,因此我最初的预感是使用 WorkManager 来保证此任务运行并将其插入到数据库。

然而,在了解 NonCancellable 协程上下文后,我想知道 withContext(NonCancellable) 是否更好。由于向数据库添加单个事件是一个非常快的操作,我想知道在这里使用 WorkManager 是否太过分了 - API 文档说 WorkManager 应该用于长时间运行的持久工作(例如网络请求等)

在哪些情况下,在处理清理的代码之外,withContext(NonCancellable) 适合在 WorkManager 上使用?

I have a simple and fast operation such as inserting an important log into an on-disk database. This needs to be guaranteed even if the user closes the app (we don't want to lose the log), and so my initial hunch was to use WorkManager to guarantee that this task runs and inserts it into the database.

However, upon learning about the NonCancellable coroutine context, I'm wondering if withContext(NonCancellable) is better. Since adding a single event to a database is a very fast operation, I'm wondering if using WorkManageris overkill here - the API documentation says WorkManager should be used for long-running, persistent work (like making network requests, etc)

What are the situations in which withContext(NonCancellable) is appropriate to be used over WorkManager, outside of code that handles cleanup?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文