C# 如何在外部提供的资源上防止ObjectDisposedException?
我有以下任务,它将偶尔运行并利用外部提供的资源C# 如何在外部提供的资源上防止ObjectDisposedException?,c#,task,dispose,objectdisposedexception,C#,Task,Dispose,Objectdisposedexception,我有以下任务,它将偶尔运行并利用外部提供的资源 // 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
// 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);
我的意图是当另一个线程触发CancellationTokenSource
上的触发器时,立即取消任务。鉴于任务大部分时间都花在缓冲区上(类型为BlockingCollection
),当抛出异常时,任务很可能会立即取消
现在我关心的是。。。如果任务在.Take
方法调用之间执行,但在this.lib.removesting
调用之前执行,则不太可能。。。lib
对象是一个外部提供的资源,因此将在外部处理(希望在执行完该线程之后)
我的代码有一天在尝试调用removesting
方法时不会抛出ObjectDisposedException
怎么说?我如何防范这种情况?你不能。即使有一个lib.IsDisposed
,它的使用也不会是线程安全的。“希望在这个线程之后…”应该确定。@HenkHolterman这怎么可能?如果因为我正在退出程序而取消,我的下一步是处理。。。如果我收到ODE怎么办?当你取消时,无论出于什么原因,你都必须在处理其资源之前执行接收.Wait()
。@HenkHolterman我曾想过,但不会接收.Wait()
立即抛出异常,完全忽略任务是否实际完成?你不能。即使有一个lib.IsDisposed
,它的使用也不会是线程安全的。“希望在这个线程之后…”应该确定。@HenkHolterman这怎么可能?如果因为我正在退出程序而取消,我的下一步是处理。。。如果我得到ODE怎么办?当你取消时,无论出于什么原因,你都必须在处理其资源之前执行接收.Wait()
。@HenkHolterman我在考虑这个问题,但不会接收.Wait()
立即抛出异常,完全忽略任务是否实际完成?