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" 
} 

답변

3

가 명시 적으로 '정지'방법을 쓰기. 변수 또는 필드를 null로 설정하여 동작을 트리거하지 마십시오.

여기서 어떻게됩니까?

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; 
} 
+1

실제로 사용하지 않는 상태가 될 수있는 클래스의 .NET 관용구이기 때문에 실제로 IDisposable을 구현합니다. –

+0

@JonHanna 그래, 그게 너무 작동합니다. 원칙은 남아 있지만, 우리는 이것을 끝낼 때 명시 적으로 말할 필요가있다. – Rob

+0

여기서'IDisposable'의 장점은 사용자에게 유용한 플래그를주고, 편리한'using' 메커니즘을 허용한다는 것이다. –

관련 문제