【发布时间】:2016-10-02 22:09:09
【问题描述】:
我正在开发一个 ReloadableCollection,它每秒在其中的后台线程上重新加载一次。问题是当我使集合的一个实例无效时,线程并没有停止(因为它不知道它正在工作的实例已被无效)。
我尝试了多种方法,例如对实例使用包装器,使 ThreadWork 方法静态并在启动时为其提供实例 (start(this)),在 Collection 的析构函数中将取消设置为 false,... 没有工作。
可以在下面的代码中看到问题的示例。
我的收藏类:
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"
}
【问题讨论】:
标签: c# multithreading garbage-collection pass-by-reference instances