.net核心API一段时间后终止方法的过程

我有一个程序将调用一种方法来验证我的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秒时,它将被答复为“超时”,但是当该方法的过程完成且在时间限制内时,它将被答复为成功。我可以知道这是否可行吗?

评论
xipsam
xipsam

.Net中有一系列ResetEvent类可以解决此问题,例如,这应该可以工作:

using System;
using System.Threading;
using System.Threading.Tasks;

public virtual IActionResult ValidatefieldPost([FromBody]Validatefield body)
        {
            var ev = new ManualResetEventSlim();
            ev.Reset();
            object ValidateFields = null;

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            // determine if you need async in the first part based on your ValidateFields
            Task.Run(async () => {
                ValidateFields = body.ValidateFields();
                ev.Set(); // important! Set after assignment
            });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            ev.Wait(15000); // your 15 seconds here

            if (ValidateFields == null)
            {
                Console.WriteLine("Timed out"); // do whatever
            }
            else
            {
                Console.WriteLine("Has result"); // do whatever
            }
        }
点赞
评论