首页 > 解决方案 > 如何在任务返回之前延迟我的任务?

问题描述

我的断言acceptor.IsStarted.Should().BeTrue();(见下面的单元测试)总是失败,因为它的评估太早了。调用await task立即返回,并没有给this.acceptor.Start()足够的时间来启动。

我想让我的启动FixAcceptor()更具确定性,因此引入了参数TimeSpan startupDelay

但是,我根本不知道在哪里以及如何延迟启动。

在andThread.Sleep(startupDelay)之间添加一个额外的内容将无济于事,因为它只会阻塞工作任务本身,而不是调用线程。this.acceptor.Start()this.IsStarted = true

我希望很清楚我想要归档什么以及我正在努力解决的问题。提前致谢。

public class FixAcceptor
{
    // Type provided by QuickFix.net
    private readonly ThreadedSocketAcceptor acceptor;

    public FixAcceptor(IFixSettings settings)
    {
        // Shortened
    }

    public bool IsStarted { get; private set; }

    public async void Run(CancellationToken cancellationToken, TimeSpan startupDelay)
    {
        var task = Task.Run(() =>
        {
            cancellationToken.ThrowIfCancellationRequested();

            this.acceptor.Start();
            this.IsStarted = true;

            while (true)
            {
                // Stop if token has been canceled
                if (cancellationToken.IsCancellationRequested)
                {
                    this.acceptor.Stop();
                    this.IsStarted = false;

                    cancellationToken.ThrowIfCancellationRequested();
                }

                // Save some CPU cycles
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }

        }, cancellationToken);

        try
        {
            await task;
        }
        catch (OperationCanceledException e)
        {
            Debug.WriteLine(e.Message);
        }
    }
}

以及对应的消费者代码

[Fact]
public void Should_Run_Acceptor_And_Stop_By_CancelationToken()
{
    // Arrange
    var acceptor = new FixAcceptor(new FixAcceptorSettings("test_acceptor.cfg", this.logger));
    var tokenSource = new CancellationTokenSource();

    // Act
    tokenSource.CancelAfter(TimeSpan.FromSeconds(10));
    acceptor.Run(tokenSource.Token, TimeSpan.FromSeconds(3));

    // Assert
    acceptor.IsStarted.Should().BeTrue();
    IsListeningOnTcpPort(9823).Should().BeTrue();

    // Wait for cancel event to occur
    Thread.Sleep(TimeSpan.FromSeconds(15));
    acceptor.IsStarted.Should().BeFalse();
}

标签: c#async-awaittask-parallel-library

解决方案


不推荐添加时间延迟来实现确定性。您可以通过使用TaskCompletionSource控制在正确的时刻完成任务来实现 100% 的确定性:

public Task<bool> Start(CancellationToken cancellationToken)
{
    var startTcs = new TaskCompletionSource<bool>();
    var task = Task.Run(() =>
    {
        cancellationToken.ThrowIfCancellationRequested();

        this.acceptor.Start();
        this.IsStarted = true;
        startTcs.TrySetResult(true); // Signal that the starting phase is completed

        while (true)
        {
            // ...
        }

    }, cancellationToken);
    HandleTaskCompletion();
    return startTcs.Task;

    async void HandleTaskCompletion() // async void method = should never throw
    {
        try
        {
            await task;
        }
        catch (OperationCanceledException ex)
        {
            Debug.WriteLine(ex.Message);
            startTcs.TrySetResult(false); // Signal that start failed
        }
        catch
        {
            startTcs.TrySetResult(false); // Signal that start failed
        }
    }
}

然后在您的测试中替换这一行:

acceptor.Run(tokenSource.Token, TimeSpan.FromSeconds(3));

...有了这个:

bool startResult = await acceptor.Start(tokenSource.Token);

引起我注意的另一个问题bool IsStarted是从一个线程发生突变并由另一个线程观察到的属性,没有同步。这不是一个真正的问题,因为您可以依赖自动插入的未记录的内存屏障 every await,并且非常有信心您不会遇到可见性问题,但是如果您想更加确定您可以通过使用来同步访问a (最健壮的),或使用这样的私有字段lock备份属性:volatile

private volatile bool _isStarted;
public bool IsStarted => _isStarted;

推荐阅读