Reputation: 11
I've developed a POST API that saves files to a specific directory. Currently, the code executes synchronously. Given that the API may receive multiple requests from clients simultaneously:
await
keyword be placed?The main tasks the API handles are:
Task 1: Reading the request content (XML).
Task 2: Creating a directory if it doesn't already exist.
Task 3: Generating a unique filename.
Finally, it saves the file to the directory.
[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));
}
Upvotes: 0
Views: 219
Reputation: 27282
Yes, it should.
When you use async with a network or IO calls, you do not block threads and they can be reused for processing other requests. But, if you have only one drive and other clients do the the same job - you will not get speed benefits, but whole system health still would be better with async calls.
Upvotes: 1