.net - Correct way to use Task.Run and Wait -


i have below block of code being launched timer:

private void checkforscheduleitemstimeronelapsed(object sender, elapsedeventargs elapsedeventargs) {     if (currentlyprocessingmsgs)         return;      currentlyprocessingmsgs = true;      var task = task.run(() => {             checkforscheduleitems.process(_cancellationtoken);         }, _cancellationtoken);      task.wait(_cancellationtoken);      currentlyprocessingmsgs = false; } 

now problem having in cases, line

currentlyprocessingmsgs = false; 

is not getting called. understanding task.wait supposed wait task complete, continue on, thereby resetting flag. in cases, not happening. (note: timer being managed service.) happening in shutdown, checking value of currentlyprocessingmsgs , it's still true after task has completed.

the goal have multiple timers being fired off 1 shown above. each timer processing similar shown above , run each process in separate thread. mistaken on understanding of cancellationtoken, in instance, correct way setup timers , tasks run through these methods , have each on separate thread?

if _cancellationtoken canceled exception raised. if want make sure flag changed if canceled or other exception raised process put currentlyprocessingmsgs = false; in try/finally block

private void checkforscheduleitemstimeronelapsed(object sender, elapsedeventargs elapsedeventargs) {     if (currentlyprocessingmsgs)         return;      currentlyprocessingmsgs = true;     try     {         var task = task.run(() => {                 checkforscheduleitems.process(_cancellationtoken);             }, _cancellationtoken);          task.wait(_cancellationtoken);     }         {         currentlyprocessingmsgs = false;     } } 

p.s. there never reason task.run wait on it. lot less overhead following should have similar logic.

private void checkforscheduleitemstimeronelapsed(object sender, elapsedeventargs elapsedeventargs) {     if (currentlyprocessingmsgs)         return;      currentlyprocessingmsgs = true;     try     {         _cancellationtoken.throwifcancellationrequested();         checkforscheduleitems.process(_cancellationtoken);     }         {         currentlyprocessingmsgs = false;     } } 

here updated version catching exception.

private void checkforscheduleitemstimeronelapsed(object sender, elapsedeventargs elapsedeventargs) {     if (currentlyprocessingmsgs)         return;      currentlyprocessingmsgs = true;     try     {         _cancellationtoken.throwifcancellationrequested();         checkforscheduleitems.process(_cancellationtoken);     }     catch (operationcanceledexception ex)     {         //if task canceled other reason our token raise exception.         if(ex.cancellationtoken != _cancellationtoken)             throw;     }         {         currentlyprocessingmsgs = false;     } } 

Comments