简体   繁体   中英

Server-side async best practices

NewbieQ: wondering about C# async / await

I have a server-side ajax request handler that is now taking too long to complete causing timeout errors.

The handler calls a method:

public bool Run(Guid jobId) // returns true if successful in running jobId

the job runs a sequence of operations that are alternately IO bound then CPU bound, in case that matters.

Ideally, I'd like to be able to launch the Run, then from time to time query the status of the run, and then get the result (the bool that Run returns).

What's the best practice when writing server-side code to do this?

Can I write a wrapper, like this?

public async Task<bool> RunAsync(Guid jobId) {...}

if so, how does that call the non-async Run?

Or do I need to do a complete re-write of the Run method? Ultimately, I'm calling this from an ajax request handler, so I need to either return the job result, or, I could change the requests so I launch the job then query from time to time for a result that has {bool resultReady, bool? result} or some struct like that.

What you really want isn't something that can be done in a simple, singular method. You really want a queueing system where you can check the status of a given message in the queue. You would essentially have a method that drops something into a queue (such as MSMQ) and another method that returns the status of a given jobId .

您可以查看hangfire,也可以signalR使用事件处理程序通知客户端,从而可能导致长时间运行的过程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM