c# - How to use cancellationToken in MVC3? -
i newbie mvc3. in project mvc3, i'm using threading import excel sheet database , works perfectly. have doubt on following, 1) how stop thread using cancellationtoken?? -- in mvc# form have following.. 2 buttons named cancel , import respectively. 2) on import button submit event have following code.
//button click on import [httppost] public actionresult finalimport(formcollection collection) { task.factory.startnew(() => { //my coding import } , tokensource.token); return null; } cancellationtokensource tokensource=new cancellationtokensource(); //button click on cancel public void canceltoken() { tokensource.token.throwifcancellationrequested(); tokensource.cancel(); // return null; } note: if click import button , while running task , click cancel button menas nothing happen.. how cancel execution of thread process. please me achieve this...
because web stateless environment, need way persist cancellation token 1 request another. finalimport , canceltoken methods separate requests. application treats each 1 being brand new, if has never seen previous request before. writing code if running in stateful environment.
the following work you.
here high level steps:
- create tokensource in finalimport method.
- add token source dictionary unique key persist requests. (say 1 declared static, global entire application).
- pass key browser.
when user presses cancel button in browser:
- have browser send key in request.
- in canceltoken dictionary key browser sends request.
- use tokensource dictionary cancel task.
- remove token dictionary.
you should also, last thing in task, remove token dictionary (otherwise build , , until run out of memory)
if, reason, process running web application should fail , iis has restart it, lose dictionary. iis restart process variety of reasons such memory pressure (e.g. things may have memory leak , creates new process work with), or because been 29 hours since last time restarted it, or because number of things. if running web garden or web farm, won't guaranteed returned same process on each request, dictionary may not available.
while realise not code solution, hope helps understanding problem domain little better.
Comments
Post a Comment