WPF 애플리케이션에 C# 코드를 따라 왔으며 이벤트 분리에 관한 질문이 있습니다.이벤트 분리
public class Publisher
{
public event EventHandler Completed;
public void Process()
{
// do something
if (Completed != null)
{
Completed(this, EventArgs.Empty);
}
}
}
public class Subscriber
{
public void Handler(object sender, EventArgs args) { }
}
사용법 : 나는 처리기 메서드를 취소하고 코드의 다음 줄을 사용하여 null로 개체를 설정 해달라고하면
여기Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
pub.Completed += sub.Handler;
// this will invoke the event
pub.Process();
내 질문은,이 응용 프로그램의 모든 메모리 누수가 발생할 것인가? 이벤트 핸들러를 등록하는 동안
pub.Completed -= sub.Handler
pub=null;sub=null;
아니요, 해당 단편에 없습니다. 게시자 개체는 코드가 포함 된 메서드의 로컬 변수에서만 참조됩니다. 따라서 pub.Publish()가 완료 될 때까지 두 객체는 동시에 가비지 수집 될 수 있습니다. 훨씬 더 오래 구독자를 유지하는 게시자는 더욱 까다로운 시나리오입니다. –