c# - 如何暂停在工作线程上运行的任务并等待用户输入?

标签 c# .net winforms async-await

如果我有一个在工作线程上运行的任务,当发现有问题时,是否可以暂停并等待用户干预后再继续?
例如,假设我有这样的东西:

async void btnStartTask_Click(object sender, EventArgs e)
{
    await Task.Run(() => LongRunningTask());
}

// CPU-bound
bool LongRunningTask()
{
    // Establish some connection here.

    // Do some work here.

    List<Foo> incorrectValues = GetIncorrectValuesFromAbove();

    if (incorrectValues.Count > 0)
    {
        // Here, I want to present the "incorrect values" to the user (on the UI thread)
        // and let them select whether to modify a value, ignore it, or abort.
        var confirmedValues = WaitForUserInput(incorrectValues);
    }
    
    // Continue processing.
}
是否可以将WaitForUserInput()替换为在UI线程上运行,等待用户干预然后采取相应措施的内容?如果是这样,怎么办?我不是在寻找完整的代码或任何东西。如果有人能指出我正确的方向,我将不胜感激。

最佳答案

您正在寻找的几乎是Progress<T>,除了您希望报告进度的东西可以将任务等待回来,并提供一些信息,他们可以等待并检查结果。 Creating Progress<T> yourself isn't terribly hard.,您可以合理地轻松调整它,以便它计算结果。

public interface IPrompt<TResult, TInput>
{
    Task<TResult> Prompt(TInput input);
}

public class Prompt<TResult, TInput> : IPrompt<TResult, TInput>
{
    private SynchronizationContext context;
    private Func<TInput, Task<TResult>> prompt;
    public Prompt(Func<TInput, Task<TResult>> prompt)
    {
        context = SynchronizationContext.Current ?? new SynchronizationContext();
        this.prompt += prompt;
    }

    Task<TResult> IPrompt<TResult, TInput>.Prompt(TInput input)
    {
        var tcs = new TaskCompletionSource<TResult>();
        context.Post(data => prompt((TInput)data)
            .ContinueWith(task =>
            {
                if (task.IsCanceled)
                    tcs.TrySetCanceled();
                if (task.IsFaulted)
                    tcs.TrySetException(task.Exception.InnerExceptions);
                else
                    tcs.TrySetResult(task.Result);
            }), input);
        return tcs.Task;
    }
}
现在,您只需要有一个异步方法,该方法从长时间运行的过程中接收数据,并返回带有用户界面响应的任务。

关于c# - 如何暂停在工作线程上运行的任务并等待用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64090710/

相关文章:

c# - TimeZoneInfo.ConvertTime 从 PST 到 UTC 到 AEST - 关闭一小时

c# - 字典的 OrderBy 方法的大 O 是什么

c# - 在 C# 中嵌套数组有更优雅的方法吗?

c# - 如何使定时器以重复的方式触发

c# - 跨线程操作问题

c# - .net core 5 中具有参数依赖关系的全局过滤器

.net - 正则表达式 正则表达式 匹配

c# - 我怎样才能让这个函数删除多行

winforms - 系统.DIINotFoundException : Failed to find library "leptonica-1.80.0.dll" for platform x86

.net - 如何使工具栏图标根据 dpi 缩放而不模糊?