2
내부의 백그라운드 스레드에서 초당 한 번 다시로드하는 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"
}
실제로 사용하지 않는 상태가 될 수있는 클래스의 .NET 관용구이기 때문에 실제로 IDisposable을 구현합니다. –
@JonHanna 그래, 그게 너무 작동합니다. 원칙은 남아 있지만, 우리는 이것을 끝낼 때 명시 적으로 말할 필요가있다. – Rob
여기서'IDisposable'의 장점은 사용자에게 유용한 플래그를주고, 편리한'using' 메커니즘을 허용한다는 것이다. –