c# - 在异步任务期间,是否有一种简单的方法可以在 UI 线程上执行方法?
问题描述
在异步方法的长时间执行过程中,使用Task.Run()
I 启动可能需要返回给用户以获得额外的输入或确认,例如必须在 UI 线程上执行的消息框或文件对话框。
有没有一种简单的方法可以做到这一点?
private void buttonApply_Click (object sender, EventArgs e) {
try {
// ...
await executeAsync (_cts.Token, progress);
} catch (OperationCanceledException) { }
// ...
}
private async Task executeAsync (CancellationToken cancellationToken, IProgress<string> progress) {
// ...
await Task.Run (() => execute (path, cancellationToken, progress), cancellationToken);
}
private void execute (string path, CancellationToken cancellationToken, IProgress<string> progress) {
// do some work, report progress, check for cancellation
// --> depending on initial work, request additional input via UI thread, how?
// do more work, based on initial work and requested input
}
解决方案
感谢您的评论,他们为我指明了正确的方向。我研究了实现,System.Progress<T>
我认为,我将从那里开始。
System.Progress<T>
捕获SynchronizationContext
并Report(T value)
调用Post()
同步上下文的异步方法。
由于我需要从我的调用中获得反馈,因此我将使用同步Send()
方法,并且可能基于一个新接口ICallbackQuery<T, TResult>
或类似的东西,仿照IProgress<T>
和Progress<T>
推荐阅读
- node.js - 如何将连续的动态音频文件从 NodeJS 流式传输到 HTML5 音频标签 - 作为一个流
- operating-system - fat中的datablock是什么意思
- python - 将每个数据从多个 numpy 传递给函数
- javascript - 如何使用动态单选按钮添加事件以显示文本框
- c++ - 编译器如何生成正确版本的模板函数,其参数在运行时知道?
- php - PHP 基于其他两个数组的数据创建数组的最佳方法
- c# - 将每个异步结果存储在其自己的数组元素中
- amazon-web-services - 使用 AWS Lambda fn 订阅一个 Amazon SNS 主题,即 sns.subscribe()?
- javascript - 我怎样才能在我的网页中只运行一次 JavaScript?
- python - 在scrapy中转换最终输出?