0

我正在尝试为 DelegatingHandler 编写一个集成测试,以防止重复请求。处理程序检查数据库以查看请求是否已被处理,如果在前一个请求仍在运行时发出重复请求,则返回 407-Conflict。

我的测试中有以下代码:

HttpClient client = new HttpClient();
var responseTask1 = client.PostAsJsonAsync(RequestUriWithDuplicatePrevention, ReadRequestContent("DuplicateRequestJsonContent.json"));
var responseTask2 = client.PostAsJsonAsync(RequestUriWithDuplicatePrevention, ReadRequestContent("DuplicateRequestJsonContent.json"));

var response1 = responseTask1.Result;
var response2 = responseTask2.Result;

两个请求同时记录到数据库中。如何将第二个请求延迟一段时间?

我试过添加一个 Thread.Sleep(500) 但它似乎没有什么不同。

修订代码

这段代码似乎大部分时间都可以工作,但它不是 100% 可靠的。

        [TestMethod]
    public void ShouldReturn407ConflictWhenDuplicateRequestSubmitted()
    {
        var results = ExecutePostRequests().Result;

        Assert.AreEqual(HttpStatusCode.OK, results[0].StatusCode);
        Assert.AreEqual(HttpStatusCode.Conflict, results[1].StatusCode);
    }

    private async Task<HttpResponseMessage[]> ExecutePostRequests()
    {
        HttpClient client = new HttpClient();

        var task1 = ExecutePost(client, 0);
        var task2 = ExecutePost(client, 4000);

        var response1 = await task1;
        var response2 = await task2;

        return new[] {response1, response2};
    }

    private async Task<HttpResponseMessage> ExecutePost(HttpClient client, int delay)
    {
        await Task.Delay(delay);
        return await client.PostAsync(RequestUriWithDuplicatePrevention,
            ReadRequestContent("DuplicateRequestJsonContent.json"));
    }

正在执行的 Web 服务有一个 Thread.Sleep(5000)。

4

1 回答 1

2

原始代码中的具体问题是它在获取结果之间处于休眠状态,而您应该在启动异步操作之间休眠。

可以这样纠正:

var responseTask1 = client.PostAsJsonAsync(...);
Thread.Sleep(2000);
var responseTask2 = client.PostAsJsonAsync(...);

var response1 = responseTask1.Result;
var response2 = responseTask2.Result;

您修改后的代码不会遇到这个问题,应该可以工作。虽然,我会改变这个:

    var response1 = await task1;
    var response2 = await task2;

    return new[] {response1, response2};

为了更高效:

    return await Task.WhenAll(task1, task2);
于 2013-11-06T05:02:24.560 回答