首页 > 解决方案 > 在异步任务期间,是否有一种简单的方法可以在 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
}

标签: c#winformsasync-await

解决方案


感谢您的评论,他们为我指明了正确的方向。我研究了实现,System.Progress<T>我认为,我将从那里开始。

System.Progress<T>捕获SynchronizationContextReport(T value)调用Post()同步上下文的异步方法。

由于我需要从我的调用中获得反馈,因此我将使用同步Send()方法,并且可能基于一个新接口ICallbackQuery<T, TResult>或类似的东西,仿照IProgress<T>Progress<T>


推荐阅读