I am creating a customized implementation handler for HTTP requests that should execute time consuming (50ms per request) code in parallel. I don't need to return anything to the user so my only concern is fast execution on a separate CPU core. This is the Configure implementation:
public void Configure(IApplicationBuilder app){
app.Run(context => {
return Task.Run(async () => {
await executeHandle(context);
});
});
}
On every request, executeHandle is called.
private static readonly Object obj = new Object();
public HashSet<string> arrayOfStrings = new HashSet();
public async Task executeHandle(HttpContext context){
if (context.Request.Body != null){
using (var ms = new MemoryStream()){
await Microsoft.AspNetCore.Http.Extensions.StreamCopyOperation.CopyToAsync(
context.Request.Body, ms, s_maxInMemoryData, context.RequestAborted);
var requestBody = ms.ToArray();
string html = Encoding.UTF8.GetString(responseBody);
// inspect arrayOfStrings HashSet on each request and execude logic based on
// items found
// build DOM tree using HTMLAgilePack or some other library, takes 50ms
// should execute in parallel, not just on a separate thread
// call BuildDomTree();
}
}
}
public static void BuildDomTree(){
// build DOM and update HashSet
lock(obj){
arrayOfStrings.add("somestring")
}
}
Since performance is critical here I'd like to hear some experts opinion on how to call BuildDomTree. Note that I do not return anything to the user, but still need the result as fast as possible. One option is to use
Task.Run(() => {BuildDomTree()});
The problem with this is that it only executes on different thread, but not necessarily in parallel. The other option is to use Parallel.For
and wrap it in Task.Run to avoid blocking:
Task.Run(() => {Parallel.For(0, 1, BuildDomTree)});
Am I overthinking optimization? Is there a better way to also execute a single function in parallel?