Monday, 15 September 2014

c# - ASP.NET MVC 4: Only allow one request at a time -



c# - ASP.NET MVC 4: Only allow one request at a time -

in asp.net mvc application, want handle requests sequentially; no action/controller code should executed concurrently another. if 2 requests come in @ similar times, should run first 1 first, sec 1 when first 1 done.

is there improve way of doing besides using global lock variable?

edit: application more of batch/service on web performs web service calls , cleans database. different urls in site lead different batch operations. not site end-users. thus, need create 1 request url (which batch operations) done @ time, otherwise batch operation corrupted if code runs concurrently itself, or other batch operations. in fact, if request comes when 1 executing, should not run @ all, after previous 1 finishes; should give error message.

i know if there way in iis instead of code. if have global lock variable, create code more complicated, , might run in deadlock lock variable set true never can set false.

edit: sample code of implementation plan

[httppost] public actionresult batch1() { //config.lock global static boolean variable if(config.lock) { response.write("error: batch process running"); homecoming view(); } config.lock = true; //run batch calls , web services (this code cannot interleaved executebatchcode2() or itself) executebatchcode(); config.lock = false; homecoming view(); } [httppost] public actionresult batch2() { if(config.lock) { response.write("error: batch process running"); homecoming view(); } config.lock = true; //run batch calls , web services (this code cannot interleaved executebatchcode1() or itself) executebatchcode2(); config.lock = false; homecoming view(); }

would need worried case code not reach config.lock = false, resulting in config.lock = true forever, causing no more requests served?

you write attribute:

public class exclusiveactionattribute : actionfilterattribute { private static int isexecuting = 0; public override void onactionexecuting(actionexecutingcontext filtercontext) { if (interlocked.compareexchange(ref isexecuting, 1, 0) == 0) { base.onactionexecuting(filtercontext); return; } filtercontext.result = new httpstatuscoderesult(httpstatuscode.serviceunavailable); } public override void onresultexecuted(resultexecutedcontext filtercontext) { base.onresultexecuted(filtercontext); interlocked.exchange(ref isexecuting, 0); } }

then utilize on controllers/methods want control:

[exclusiveaction] //either here, every action in controller public class mycontroller : controller { [exclusiveaction] //or here specific methods public actionresult dothething() { //foo homecoming someactionresult(); } }

c# asp.net-mvc request sequential controller-action

No comments:

Post a Comment