Azure Functions 使用带有 Http 触发器的取消令牌 [英] Azure Functions using Cancellation Token with Http Trigger

查看:22
本文介绍了Azure Functions 使用带有 Http 触发器的取消令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用取消令牌在 Azure 中开发一个函数.它是一个 Http 触发器.

I am developing a Function in Azure with Cancellation Token. Its an Http Trigger.

我在方法参数中传入了一个Cancellation Token.

I pass in a Cancellation Token in in the method parameters.

它的长期运行功能.我在进程之间取消了请求,但进程继续运行并且取消令牌没有影响.

Its long running function. And I cancel the request in between of the process but the process keeps running and the cancellation token doesn't take its affect.

Azure Functions 是否支持此功能,如果我在其间取消 Http 请求,它也应该取消其执行,但事实并非如此.

Is this supported in Azure Functions, that if I cancel a Http Request in between it should also cancel its execution but this is not the case.

我通过一小段代码对此进行了测试

I tested this via small piece of code

public static class LongRunningFunction
    {
        [FunctionName("LongRunningFunction")]
        public static async Task<IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",  Route = "Long")]
            HttpRequest req, ILogger log, CancellationToken token)
        {
            try
            {
                await Task.Delay(10000, token);
                return new OkResult();

            }
            catch (OperationCanceledException)
            {
                return new NotFoundResult();
            }
            catch (Exception e)
            {
                return new InternalServerErrorResult();
            }
        }
    }

我使用 Postman 执行死刑.

And I used Postman for the execution.

我做错了吗?

我正在从以下 链接

推荐答案

我知道这是一个老问题,但我找到了这个问题的答案.

I know this is an old question, but I found the answer to this issue.

在 Azure Functions 中,有 2 个取消令牌.

In Azure Functions, there are 2 cancellation tokens.

Function Method 参数中传递的令牌是Host Cancellation Token - 当主机即将关闭时请求取消.

The token passed in Function Method parameter is the Host Cancellation Token - cancellation is requested when the host is about to shut down.

另一个标记是 req.HttpContext.RequestAborted 属性.当浏览器取消请求时它被取消 - 这就是你所追求的.

The other token is req.HttpContext.RequestAborted property. It's being cancelled when browser cancels the request - this is what you were after.

另外,您可以使用以下代码:

In addition, you can use following code:

using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(hostCancellationToken, req.HttpContext.RequestAborted);

获取在主机或请求被取消时取消的令牌.

To get a token that cancels when either host or request is being cancelled.

这篇关于Azure Functions 使用带有 Http 触发器的取消令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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