c# - 如何正确实现自定义等待者的OnCompleted方法?

标签 c# async-await

我有一个自定义等待类型,问题是继续在不同的线程上恢复,这会导致 UI 出现问题,例如 WinForms/WPF/MVC/等:

private MyAwaitable awaitable;

private async void buttonStart_Click(object sender, EventArgs e)
{
    awaitable = new MyAwaitable(false);
    progressBar1.Visible = true;

    // A regular Task can marshal the execution back to the UI thread
    // Here ConfigureAwait is not available and I don't know how to control the flow
    var result = await awaitable;

    // As a result, here comes the usual "Cross-thread operation not valid" exception
    // A [Begin]Invoke could help but regular Tasks also can handle this situation
    progressBar1.Visible = false;
}

private void buttonStop_Click(object sender, EventArgs e) => awaitable.Finish();

这是 MyAwaitable类:

public class MyAwaitable
{
    private volatile bool finished;
    public bool IsFinished => finished;
    public MyAwaitable(bool finished) => this.finished = finished;
    public void Finish() => finished = true;
    public MyAwaiter GetAwaiter() => new MyAwaiter(this);
}

还有有问题的自定义等待者:

public class MyAwaiter : INotifyCompletion
{
    private readonly MyAwaitable awaitable;
    private readonly SynchronizationContext capturedContext = SynchronizationContext.Current;

    public MyAwaiter(MyAwaitable awaitable) => this.awaitable = awaitable;
    public bool IsCompleted => awaitable.IsFinished;

    public int GetResult()
    {
        var wait = new SpinWait();
        while (!awaitable.IsFinished)
            wait.SpinOnce();
        return new Random().Next();
    }

    public void OnCompleted(Action continuation)
    {            
        // continuation(); // This would block the UI thread

        // Task constructor + Start was suggested by the references I saw,
        // Results with Task.Run/Task.Factory.StartNew are similar.
        var task = new Task(continuation, TaskCreationOptions.LongRunning);

        // If executed from a WinForms app, we have a WinFormsSyncContext here,
        // which is promising, still, it does not solve the problem.
        if (capturedContext != null)
            capturedContext.Post(state => task.Start(), null);
        else
            task.Start();
    }
}

我怀疑我的 OnCompleted实现不太正确。

我试图深入研究 ConfiguredTaskAwaiterTask.ConfigureAwait(bool).GetAwaiter() 返回方法,可以看到黑魔法发生在 SynchronizationContextAwaitTaskContinuation 中。类,但这是一个内部类,以及许多其他内部使用的类型。有没有办法重构我的 OnCompleted实现是否按预期工作?

更新:投反对票者注意:我知道我在 OnCompleted 做了不当的事情,这就是我问的原因。如果您对质量(或其他任何问题)有疑虑,请发表评论并帮助我改进问题,这样我也可以帮助您更好地突出问题。谢谢。

注意 2:我知道我可以使用 TaskCompletionSource<TResult> 的解决方法及其常规 Task<TResult>结果,但我想了解背景。 这是唯一的动力。纯粹的好奇心。

更新 2:我调查过的著名引用资料:

服务员的工作原理:

一些实现:

最佳答案

OnCompleted 的 MSDN 解释方法是:

Schedules the continuation action that's invoked when the instance completes.

因此 OnCompleted 的实现都不是“正确的”,因为如果 awaitable 尚未完成,但将其注册为在 awaitable 完成时执行。

唯一不清楚的是,如果 awaitable 在调用方法时已经完成,则该方法应该做什么(尽管编译器生成的代码在这种情况下不会调用它)——忽略继续委托(delegate)或执行。根据Task的实现,应该是后者(execute)。

当然也有异常(exception)的规则(“正确” 一词的由来)。例如,YieldAwaiter 特别总是返回 IsCompleted == false 以强制调用它的 OnCompleted 方法,该方法会立即在线程池上安排传递的委托(delegate).但“通常”你不会那样做。

通常(与标准的 Task 实现一样)awaitable 将执行操作、提供结果、等待机制,并将维护/执行延续。它们的 awaiters 通常是 struct,持有对共享 awaitable 的引用(以及需要时的继续选项),并将委托(delegate) GetResult OnCompleted 方法调用共享的 awaitable,特别是 OnCompleted 将延续委托(delegate)和选项传递给 >awaitable 负责注册/执行它们的内部方法。 “可配置的”awaitable 将简单地保存共享的awaitable 加上选项,并将它们简单地传递给创建的awaiter

由于在您的示例中等待和结果由 awaiter 提供,因此 awaitable 可以简单地提供完成事件:

public class MyAwaitable
{
    private volatile bool finished;
    public bool IsFinished => finished;
    public event Action Finished;
    public MyAwaitable(bool finished) => this.finished = finished;
    public void Finish()
    {
        if (finished) return;
        finished = true;
        Finished?.Invoke();
    }
    public MyAwaiter GetAwaiter() => new MyAwaiter(this);
}

等待者会订阅它:

public class MyAwaiter : INotifyCompletion
{
    private readonly MyAwaitable awaitable;
    private int result;

    public MyAwaiter(MyAwaitable awaitable)
    {
        this.awaitable = awaitable;
        if (IsCompleted)
            SetResult();

    }
    public bool IsCompleted => awaitable.IsFinished;

    public int GetResult()
    {
        if (!IsCompleted)
        {
            var wait = new SpinWait();
            while (!IsCompleted)
                wait.SpinOnce();
        }
        return result;
    }

    public void OnCompleted(Action continuation)
    {
        if (IsCompleted)
            {
                continuation();
                return;
            }
        var capturedContext = SynchronizationContext.Current;
        awaitable.Finished += () =>
        {
            SetResult();
            if (capturedContext != null)
                capturedContext.Post(_ => continuation(), null);
            else
                continuation();
        };
    }

    private void SetResult()
    {
        result = new Random().Next();
    }
}

OnCompleted 被调用时,首先我们检查是否完成。如果是,我们只需执行传递的委托(delegate)并返回。否则,我们捕获同步上下文,订阅 awaitable 完成事件,并在该事件中通过捕获的同步上下文或直接执行操作。

同样,在现实生活场景中,awaitable 应该执行真正的工作,提供结果并维护后续操作,而 awaiter 应该只注册后续操作,最终抽象出继续执行策略——直接地,通过捕获的同步上下文,通过线程池等。

关于c# - 如何正确实现自定义等待者的OnCompleted方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375326/

相关文章:

c# - 禁用特定 C# 类的所有 stylecop 警告

c# - HttpClient GetAsync 线程池饥饿

python - 如何在 Python 3.6 中使用异步生成器?

c# - 使用 Moq 针对异步方法设置 C# 测试

C# 在委托(delegate)调用中等待

c# - 如何使用 Entity Framework Core 可视化设计我的数据库?

c# - 编译错误 :A field initializer cannot reference the non-static field, 方法或属性

c# - 静默更新 Windows 服务

c# - 为什么刷新列表后列表中的选定项目会移动到不同的屏幕位置

c# - 始终使用异步/等待在 ASP.NET Web 窗体中的浏览器中加载页面