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

ICl*_*ble 6 .net c# 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.
}
Run Code Online (Sandbox Code Playgroud)

是否可以WaitForUserInput()用在 UI 线程上运行的东西来替代,等待用户的干预,然后采取相应的行动?如果是这样,如何?我不是在寻找完整的代码或任何东西;如果有人能指出我正确的方向,我将不胜感激。

Ser*_*rvy 9

您正在寻找的内容几乎完全相同Progress<T>,除了您希望报告进度的事情返回带有一些信息的任务,他们可以等待并检查其结果。 创造Progress<T>自己并不难。,并且您可以合理地轻松调整它,以便它计算结果。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您只需要一个异步方法来接受来自长时间运行的进程的数据并返回一个任务,无论用户界面的响应是什么。