如何从其中的工作线程检测 object 的无效

How to detect nullification of an object from a working thread inside it

我正在开发一个 ReloadableCollection,它在其中的后台线程上每秒重新加载一次。问题是,当我使 collection 的实例无效时,线程不会停止(因为它不知道它正在工作的实例已被无效)。

我尝试了多种方法,比如为实例使用包装器,使 ThreadWork 方法静态化并在启动时为它提供实例 (start(this)),在 [=25= 的析构函数中将 cancel 设置为 false ], ... 没有任何效果。

问题的示例可以在下面的代码中看到。

我的collectionclass:

class Collection
{
    private const int INTERVAL=1000;

    Thread thread;

    public Collection()
    {
        thread=new Thread(ThreadWork);
        thread.Start();
    }

    private void ThreadWork()
    {
        while(true){ // how to detect when the instance is nullified?
            Reload();
            Thread.Sleep(INTERVAL);
        }
    }

    private void Reload()
    {
        // reload the items if there are any changes
    }
}

用法示例:

void Main()
{
    Collection myCollection=new Collection();

    // ...
    // here, it is reloading, like it should be
    // ...

    myCollection=null;

    // ...
    // here, it should not be reloading anymore, but the thread is still running and therefore "reloading"
}

写一个明确的'Stop'方法。不要通过将变量或字段设置为空来触发行为。

这里发生了什么?

Collection myCollection = new Collection();
var myOtherCollection = myCollection;
myCollection = null; //Should it stop here?
myOtherCollection = null; //And now? Both are null.

Collection myCollection = new Collection();
MyMethod(myCollection);
myCollection = null; //And here? What if MyMethod adds the collection to a list, or keeps track of it?

void Test()
{
    Collection myCollection = new Collection();
} //Should it stop reloading when we exit the method?

只需告诉集合在完成后停止重新加载即可。你会避免更多的头痛,我保证。

private volatile bool _stopping;
private void ThreadWork()
{
    while (!_stopping)
    {
        Reload();
        Thread.Sleep(INTERVAL);
    }
}

public void Stop()
{
    _stopping = true;
}