I have a class WorkerTaskEvent : IDisposable
which has a property of type Task
. On creation, it will create a new task, which will run some method in the background which is supposed to end at some point.
However, sometimes the task does not end, thus keeping things in memory forever. Right now I use a cancellation token to send a cancel message and I do this like 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 to check if the task ends within a specific amount of time.)
I can't have this task running forever and I'm hoping this is a proper solution, but perhaps someone else has a better option?
I have absolutely no control over what TaskMethod will do exactly, so if any resources are lost when this method is killed, fine. Far from perfect, though. But clean-up will be the responsibility of those who create the method behind this delegate.
While passing a cancellation token to the delegated method might help a lot, I can't use this as a solution since the delegated method is part of a third-party library and it's not supposed to end in an endless loop. Murphy's law is laughing me in my face again, since the delegate does tend to loop endlessly, though. Maybe I can pass a cancellation token in the next version of this library (I've requested this) but for now I have to stop the endless loop in a hard way...