c# - Use Async Method at Service Layer from MVC 5? -


i developing asp.net mvc 5 application. have been reading questions here suggest not use type of behavior want.

high level of want achieve -

mvc controller - calls method @ service layer , continues next line of code in controller not need return anything.

method in service layer - want to call external web service has async methods want these run off on , write data db when return.

is achievable or not best approach?

to dummy out , test principle have following on controller:

    [acceptverbs(httpverbs.post)]     public actionresult testasync()     {         _myservice.testasync();          return redirecttoaction("summary");     } 

at _myservice method looks follows:

    public async task testasync()     {         await task.delay(10000);          var test = "testing";         _testrepository.add(test);     } 

i hoping testasync method wait 10 seconds , check db , value testing added. not working - on ui after hitting button page goes summary view , await task.delay breakpoint hit next lines never execute. there incorrect approach? should testasync method like:

    public void testasync()     {        //call private async method here in class task delay        //which similar calling actual async external web service methods         var test = "testing";         _testrepository.add(test);     } 

i have been reading questions here suggest not use type of behavior want.

that's because it's dangerous. asp.net decides it's safe unload appdomain when there no active requests, if return controller action while still have work do, asp.net not aware of work.

the best solution set reliable queue (such azure queue) separate backend (such azure webjob) processes queue in reliable way. correct solution, lots of people won't because it's complex.

if have sql server or redis database in solution, consider hangfire. hangfire uses database reliable queue, , executes backend alongside asp.net application.

if want live dangerously, @ least should use hostingenvironment.queuebackgroundworkitem, inform asp.net of work application doing outside of request.

is there incorrect approach?

yes; _myservice.testasync attempting resume on request context request has completed.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -