c# 4.0 - How to cancel a task or terminate the task execution instantly? -


i have windows service developed in c#. on it's start method have initialization such as:

task _backgroundtask = null;  cancellationtokensource _backgroundcancellationsource = null;  protected override void onstart(string[] args) {  ......  _backgroundcancellationsource = new cancellationtokensource();  cancellationtoken token = backgroundcancellationsource.token;  _backgroundtask = new task(() => backgroundfoldersprocessing(token), token, taskcreationoptions.longrunning);  ....... } 

now method backgroundfoldersprocessing looks this:

void backgroundfoldersprocessing(cancellationtoken token) {              while (true)             {                 try                 {                     if (token.iscancellationrequested)                     {                                                 return;                     }                      dosomework()                 }                 catch (exception ex)                 {                     .........                 }             } } 

now, stop method follows:

protected override void onstop() { .................  _backgroundcancellationsource.cancel(); _backgroundtask.wait();  _backgroundcancellationsource.dispose(); _backgroundtask.dispose();  _backgroundtask = null; _backgroundcancellationsource = null;  ................. } 

now problem when try stop service in middle of processing, wait method of _backgroundtask not stop service until , unless dosomework() method inside backgroundfoldersprocessing gets completed, windows service not stop.

is there way, though can stop service , execution of _backgroundtask terminated, though dosomework() method gets completed/executed or not? have tried token.throwifcancellationrequested() in backgroundfoldersprocessing method, did not worked. want whenever try stop service service control manager (scm), service should stopped , __backgroundtask should stop executing backgroundfoldersprocessing method , terminated well. how can achieve this?

you can try use threadabortexception:

defining thread:

threadstart threaddelegate = new threadstart(backgroundfoldersprocessing); thread thread_ = new thread(threaddelegate); thread_.start(); 

add catch backgroundfoldersprocessing

catch (threadabortexception e) {      return; } 

and when want shut down use:

thread_.abort(); thread_.join(); 

then when abort() called threadabortexception thrown.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -