multithreading - Disposing an object with a running task? -


i have class workertaskevent : idisposable has property of type task. on creation, create new task, run method in background supposed end @ point.
however, task not end, keeping things in memory forever. right use cancellation token send cancel message , this:

public workertaskevent(executetaskmethod taskmethod) {     taskmethod = taskmethod;     runningtask = task.factory.startnew(onexecutetask, token.token);  }  private void onexecutetask() {     if (taskmethod != null) taskmethod(); }  public void dispose() {     if (runningtask != null && !runningtask.iscompleted)     {         token.cancelafter(timespan.fromminutes(1));     } } 

(there's more code, including code check if task ends within specific amount of time.)
can't have task running forever , i'm hoping proper solution, perhaps else has better option?
have absolutely no control on taskmethod exactly, if resources lost when method killed, fine. far perfect, though. clean-up responsibility of create method behind delegate.

while passing cancellation token delegated method might lot, can't use solution since delegated method part of third-party library , it's not supposed end in endless loop. murphy's law laughing me in face again, since delegate tend loop endlessly, though. maybe can pass cancellation token in next version of library (i've requested this) have stop endless loop in hard way...

task cancellation co-operative , should not forced.

when pass cancellation token task.factory.startnew() case when token source cancelled before task scheduled. however, once task has started running, responsibility of running delegate check , stop on cancelled token.

hence should define delegate executetaskmethod such accepts cancellationtoken parameter. leave delegate implementer cancel on token.

private void onexecutetask() {     if (taskmethod != null) taskmethod(token.token); } 

also see answer here: how abort/cancel tpl tasks?


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -