通过 async/await 提高 POST API 可扩展性

问题描述 投票:0回答:1

我开发了一个 POST API,可以将文件保存到特定目录。目前,代码同步执行。鉴于 API 可能会同时接收来自客户端的多个请求:

使代码异步会提高可扩展性和性能吗? 代码中的所有方法都应该异步吗? wait关键字应该放在哪里?

API 处理的主要任务是:

任务1:读取请求内容(XML)。

任务 2:创建一个目录(如果该目录尚不存在)。

任务 3:生成唯一的文件名。

最后将文件保存到目录中。

  [System.Web.Mvc.HttpPost]
    public IHttpActionResult Post(HttpRequestMessage request)
    {
        try
        {
            string contentResult = string.Empty;
            ValidateRequest(ref contentResult, request);
            //contentResult = "nothing";
            //Validation of the post-requested XML 
            //XmlReaderSettings(contentResult);
           
            using (StringReader s = new StringReader(contentResult))
            {
                doc.Load(s);
            }

            string path = MessagePath;

            //Directory creation
            DirectoryInfo dir = Directory.CreateDirectory($@"{path}\PostRequests");
            
            string dirName = dir.Name;

            //Format file name
            var uniqueFileName = UniqueFileNameFormat();

            doc.Save($@"{path}\{dirName}\{uniqueFileName}");
        }
        catch (Exception e)
        {
            LogService.LogToEventLog($"Error occured while receiving a message from messagedistributor: " + e.ToString(), System.Diagnostics.EventLogEntryType.Error);
            throw e;
        }
        LogService.LogToEventLog($"Message is received sucessfully from messagedistributor: ", System.Diagnostics.EventLogEntryType.Information);
        return new ResponseMessageResult(Request.CreateResponse((HttpStatusCode)200));
    }
c# api post async-await task
1个回答
2
投票

是的,应该如此。

当您将异步与网络或 IO 调用结合使用时,您不会阻塞线程,并且它们可以被重用来处理其他请求。 但是,如果您只有一个驱动器并且其他客户端执行相同的工作 - 您将不会获得速度优势,但通过异步调用,整个系统的运行状况仍然会更好。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.