【问题标题】:Kill process of method after a period of time .net core API一段时间后杀死方法的进程.net core API
【发布时间】:2020-05-17 05:28:36
【问题描述】:

我有一个程序会调用一个方法来验证我的 API 中请求的参数

public virtual IActionResult ValidatefieldPost([FromBody]Validatefield body)
        {
            dynamic ValidateFields = body.ValidateFields();

            string exampleJson = null;  
            exampleJson = "{\n  \"updateMessage\" : \"Common Field was validated.\"\n}";

            var example = exampleJson != null
            ? JsonConvert.DeserializeObject<Successful>(exampleJson)
            : default(Successful);
            if (body.isSuccess)
            {

                    return Ok("Validate is successfull");


            }
            else
            {
                        return BadRequest(ValidateFields);
            }
        }

我想在这个过程中设置一个类似“15秒”的计时器

Validatefieds=body.Validatefields();

这样当进程到达15秒时,它会回复为“超时”,但是当方法的进程完成并在时限内时,它会回复为成功。我可以知道这是否可能吗?

【问题讨论】:

    标签: c# api .net-core timer


    【解决方案1】:

    基本上,只需将您的工作包装在一个“任务”中,然后等待它完成:

    using System.Threading.Tasks;
    
    public virtual IActionResult ValidatefieldPost([FromBody]Validatefield body, CancellationToken cancellationToken)
            {
                object ValidateFields = null;
                var cts = new CancellationTokenSource();
    
                object result = null;
                var task = Task.Run(() =>
                {
                    result = body.ValidateFields();
                }, cts.Token);
    
                task.Wait(15000, cancellationToken); // 15 seconds timeout
    
                if (result == null)
                {
                    Console.WriteLine("Timed out");  // do whatever
                    cts.Cancel(); // to cancel the work inside your validation, might want to pass the CT down the stack
                }
                else
                {
                    Console.WriteLine("Has result"); // do whatever
                }
        }
    

    请注意我们如何连接到 CancellationToken 传递到 ASP .Net Core 管道,这样您就不会因长时间等待而陷入资源困境。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多