基于任务的超时,激活速度低于预期

时间:2015-03-19 16:10:27

标签: c# windows-phone-8 timeout async-await task

我有一个HttpMessage,它在某些时候需要一个结果。我希望用户能够在设置响应之后或超时之后等待返回ether的任务。在运行我的单元测试时,它可以工作,但只有当我设置超时时间比响应的延迟设置更早。

为什么会发生这种情况,我有什么办法可以收紧时机。

*请注意下面的单元测试有效,但如果将延迟设置为500毫秒,则失败

HttpMessage代码:

public async Task<bool> ContinueWhenResponseRecieved(int Timeout)
        {
            NotifyTaskCompletionSource = new TaskCompletionSource<bool>();
            bool result = true;
            //If we have already recieved a response return true;
            if (this._response != null)
            {
                return result;
            }
            //If Timeout is not 0 then start a task that after the timeout period will set the completion source to true no matter what
            if (Timeout != 0) 
            {
                TaskEx.Run(async () =>
                {
                    await TaskEx.Delay(Timeout);
                    result = false;
                    try
                    {
                        NotifyTaskCompletionSource.SetResult(true);
                    }
                    catch (Exception ex) { } //ignore race condition issues
                });
            }
            await NotifyTaskCompletionSource.Task;
            return result;
        }
        public override IHttpMessage setResponse(HttpResponse _response)
        {
            if (NotifyTaskCompletionSource != null)
            {
                try
                {
                    NotifyTaskCompletionSource.SetResult(true);
                }catch(Exception ex){} //Ignore race condtion issues
            }
            return base.setResponse(_response);
        }

单元测试:

  [TestMethod]
    public async Task TestNotifiableTimeOuts()
    {
        var msg = new NotifiableHttpMessage();
        TaskEx.Run(() =>
        {
            TaskEx.Delay(1000).Wait();
            msg.setResponse(new Messages.HttpResponse());
        });
        var result= await msg.ContinueWhenResponseRecieved(50);

        Assert.IsFalse(result);
    }

1 个答案:

答案 0 :(得分:0)

归功于Servy

问题是单元测试不是异步的,并且导致了问题。一个完全刷新的异步测试就可以了。最终结果单元测试:

[TestMethod]
    public async Task TestNotifiableTimeOuts()
    {
        var msg = new NotifiableHttpMessage();
        TaskEx.Run(async () =>
        {
            await TaskEx.Delay(200);
            msg.setResponse(new Messages.HttpResponse());
        });
        var result= await msg.ContinueWhenResponseRecieved(50);

        Assert.IsFalse(result);
    }