Using a CancellationTokenSource on a task thats acquires a lock
If the thread acquires the lock when the cancelation occures, it does not release the lock
BTW, the thread needs to stop immediately, without finnishing the work
This is an example for such a code:
var cancellationTokenSource = new CancellationTokenSource;
Task.Run(new Action (() =>
{
while(true)
{
lock (locker)
{
DoSomething();
}
DoAnotherThing();
Task.Delay(1000, cancellationTokenSource.Token);
}
}), cancellationTokenSource.Token);
I've found several ways to handle it, but I've wanted to hear some suggestions
Thanks
EDIT: To answer @spender question, this is the implementation a thought of (shortened) :
object locker = new object();
var cancellationTokenSource = new System.Threading.CancellationTokenSource;
var token = cancellationTokenSource.Token;
Task.Run(new Action (() =>
{
while(true)
{
lock (locker)
{
using (token.Register(() => token.ThrowIfCancellationRequested()))
{
break;
};
DoSomething();
}
DoAnotherThing();
Task.Delay(1000, cancellationTokenSource.Token);
}
}), cancellationTokenSource.Token);