Finalizers and Dispose

后端 未结 6 1549
失恋的感觉
失恋的感觉 2021-01-01 06:04

I\'ve got a class named BackgroundWorker that has a thread constantly running. To turn this thread off, an instance variable named stop to needs to

6条回答
  •  有刺的猬
    2021-01-01 07:01

    The object that implements the finalizer needs a reference to a flag--stored in another object--which the thread will be able to see; the thread must not have any strong reference, direct or indirect, to the object that implements the finalizer. The finalizer should set the flag using something like a CompareExchange, and the thread should use a similar means to test it. Note that if the finalizer of one object accesses another object, the other object may have been finalized but it will still exist. It's fine for a finalizer to reference other objects if it does so in a way that won't be bothered by their finalization. If all you're doing is setting a flag, you're fine.

提交回复
热议问题