I've got the following task which will run occasionally and utilize externally provided resources.
// start receiving the data
receiving = Task.Run(() =>
{
string dataCopy = string.Empty;
string next = string.Empty;
while (true)
{
next = this.buffer.Take(t);
if(!string.IsNullOrEmpty(next))
{
// keep appending the data
dataCopy += next;
// check if we've gotten the EOL
if(dataCopy.Contains(endOfLine))
{
// remove the EOL
dataCopy = this.lib.RemoveString(dataCopy, endOfLine);
break;
}
}
t.ThrowIfCancellationRequested();
}
return dataCopy;
}, t);
My intent here is to have the task cancel immediately when another thread pulls the trigger on the CancellationTokenSource
. Which, seeing as the task spends most of its time sitting on buffer
(which is of type BlockingCollection
) the task will most likely cancel immediately when .Take
throws its exception.
Now here is my concern... on the off-chance that the task is executing somewhere between the .Take
method call but before the this.lib.RemoveString
call... The lib
object is an externally provided resource and as such will be disposed of externally (hopefully after this thread is done executing).
What's to say that my code won't one day throw an ObjectDisposedException
on trying to call the RemoveString
method? How can I safeguard against that scenario?