具有超时处理的异步Web请求的最佳模式 [英] Best pattern for async web requests with timeout handling

查看:111
本文介绍了具有超时处理的异步Web请求的最佳模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要在短时间内将这些内容放在一起,因为研究时间非常有限,所以我们对此表示赞赏。我们需要从我们自己的本地REST MVC服务内部向外部服务发出异步Web请求。请求将响应(简单部分)
或超时,如果超时,我们必须发送第二个CANCEL请求,然后我们就完成了。

We need to put this together at short notice and any advice is appreciated as research time is very limited. We need to make async web requests to an external service from inside our own local REST MVC service. The request will either respond (easy part) or timeout, if it times out we must send a second CANCEL request and then we're done.

假设.Net Framework 4.6和VS 2017任何支持的C#语言版本都可以,如果这有帮助,RestSharp也可用。

Assume .Net Framework 4.6 and VS 2017 any supported version of C# language is fine, RestSharp is available too if this helps.

我认为这是微不足道的(可能是!)但是初始网络搜索给出了我的印象并不像我希望的那么简单。

I'd assumed this was trivial (and it may be!) but initial web search gives me the impression this isn't as straightforward as I'd hoped.

推荐答案

取决于网络请求。如果这是一个REST API调用,那么你将使用支持取消的HttpClient。如果您通过WebClient或类似方式进行HTTP调用,则可能更难。

Depends upon the web request. If this is to a REST API call then you'll be using HttpClient which supports cancellation. If you're making an HTTP call via WebClient or similar it may be harder.

这是一些未经测试的代码。还有其他方法可以做到这一点。

Here's some untested code. There are other ways of doing it as well.

class Program
{
    static void Main ( string[] args )
    {
        //Create a cancellation source
        var cancellation = new CancellationTokenSource();

        //Start long running task (10 seconds)
        var task = LongRunningProcessAsync(10, cancellation.Token);
            
        //Wait for it to complete or 5 seconds
        if (!task.Wait(5000))
        {
            //Took too long so cancel it
            cancellation.Cancel();
        };

        //Task will be cancelled at some point hereafter
    }

    static Task LongRunningProcessAsync ( int count, CancellationToken cancellationToken )
    {
        return Task.Run(() => {
            for (var index = 0; index < count; ++index)
            {
                Console.WriteLine(index);
                Thread.Sleep(1000);
            };
        }, cancellationToken);
    }
}


基本上你启动请求异步。然后你等待它完成 - 注意这是一个阻塞的电话。如果在等待完成之前没有完成,则取消它。如果您需要取消阻止,那么您可以在
a之后设置一个计时器以取消令牌。

Basically you start the request async. Then you wait for it to complete - note this is a blocking call. If it doesn't complete before your wait is done then you cancel it. If you need to do this unblocked then you can set up a timer to cancel the token after a given amount of time instead.


这篇关于具有超时处理的异步Web请求的最佳模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆